Generate HTML List From JavaScript Array

Ciprian on Wednesday, January 10, 2018 in JavaScript Arrays & Objects, JavaScript DOM

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

How to 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(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. See it as the third solution below.
Check out this jsPerf test in a modern browser.

Solution 3

const options = [
    set0 = ['Option 1','Option 2'],
    set1 = ['First Option','Second Option','Third Option']

function makeUL(array) {
    // Create the list element
    let list = document.createElement('ul');

    for (let i = 0; i < array.length; i++) {
        // Create the list item
        let item = document.createElement('li');

        // Set its contents

        // Add it to the list

    // Finally, return the constructed list
    return list;

// Add the contents of options[0] to #foo:

 * Usage
 * Add an element to hold the data:
 * <div id="foo"></div>

// or


This solution can be extended to pass an element parameter to the makeUL() function and display different arrays in different elements.

Related posts

Leave a Reply

You have to agree to the comment policy.