Generate HTML List From JavaScript Array

ūüĎč Ciprian on Wednesday, January 10, 2018 in Blog, JavaScript
Last modified on Friday, August 23, 2019

Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

Generate an HTML ul/li list based on the contents of a JavaScript array or how to create a JavaScript list.

By modifying the makeList() function to accept parameters and target elements, you can pass different arrays and generate different lists inside different containers.

Solution 1

This vanilla JavaScript function has zero dependencies and works in all browsers.

function makeList() {
    // Establish the array which acts as a data source for the list
    let listData = [
        'Blue',
        'Red',
        'White',
        'Green',
        'Black',
        'Orange'
    ],
    // Make a container element for the list
    listContainer = document.createElement('div'),
    // Make the list
    listElement = document.createElement('ul'),
    // Set up a loop that goes through the items in listItems one at a time
    numberOfListItems = listData.length,
    listItem,
    i;

    // Add it to the page
    document.getElementsByTagName('body')[0].appendChild(listContainer);
    listContainer.appendChild(listElement);

    for (i = 0; i < numberOfListItems; ++i) {
        // create an item for each one
        listItem = document.createElement('li');

        // Add the item text
        listItem.innerHTML = listData[i];

        // Add listItem to the listElement
        listElement.appendChild(listItem);
    }
}

// Usage
makeList();

See a JSFiddle demo here.

Solution 2

This function is more compact and uses a forEach() loop:

let items = [
        'Blue',
        'Red',
        'White',
        'Green',
        'Black',
        'Orange'
    ],
    ul = document.createElement('ul');

document.getElementById('myItemList').appendChild(ul);

items.forEach(function (item) {
    let li = document.createElement('li');
    ul.appendChild(li);

    li.innerHTML += item;
});

Here’s another way of doing it, similar to the first solution. Note that the forEach() loop is marginally slower.
Check out this jsPerf test in a modern browser.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Buy me a coffee to support my work!

ūüĎč Added by Ciprian on Wednesday, January 10, 2018 in Blog, JavaScript. Last modified on Friday, August 23, 2019.

Leave a Reply

You have to agree to the comment policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy