getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

Generate HTML List From JavaScript Array

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
    var listData = [
        'Blue',
        'Red',
        'White',
        'Green',
        'Black',
        'Orange'
    ];

    // Make a container element for the list
    var listContainer = document.createElement('div');

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

    // Make the list
    var listElement = document.createElement('ul');

    // Add it to the page
    listContainer.appendChild(listElement);

    // Set up a loop that goes through the items in listItems one at a time
    var numberOfListItems = listData.length;

    for (var i = 0; i < numberOfListItems; ++i) {
        // create an item for each one
        var 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:

var items = [
        'Blue',
        'Red',
        'White',
        'Green',
        'Black',
        'Orange'
    ];

var ul = document.createElement('ul');

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

items.forEach(function (item) {
    var 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.

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.


Privacy Policy