Generate HTML List From JavaScript Array

Follow me!

If you like this article, go ahead and follow me on Twitter:

Follow @getButterfly

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Ā =Ā [
    // 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,

    // Add it to the page

    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

// Usage

See a JSFiddle demo here.

Solution 2

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

let items = [
    ul = document.createElement('ul');


items.forEach(function (item) {
    let li = document.createElement('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.

šŸ‘‹ Added by Ciprian on Wednesday, January 10, 2018 in Blog, JavaScript. Last modified on Friday, August 23, 2019.


Contribute to this article by sharing your opinion on Twitter:

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. Itā€™s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started
Privacy Policy