Generate HTML List From JavaScript Array

by Ciprian Popescu

HTML

<p>Based on this <a href="https://getbutterfly.com/generate-html-list-from-javascript-array/">getButterfly.com JavaScript tutorial</a>.</p>

CSS

body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    font-size: 14px;
    line-height: 1.5;
    color: #24292e;
    background-color: #fff;
}

JavaScript

/**
 * Generate HTML List From JavaScript Array
 *
 * @source https://getbutterfly.com/generate-html-list-from-javascript-array/
 */
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
    let listContainer = document.createElement('div');
    // Make the list
    let listElement = document.createElement('ul');
    // Make the list item
    let listItem = document.createElement('li');

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

    // Set up a loop that goes through the items in listItems one at a time
    let numberOfListItems = listData.length;
    for (let i = 0; i < numberOfListItems; ++i) {
        // Add the item text

		// Use this if the array elements contain HTML
        // listItem.innerHTML = listData[i];
        // If not, use the line below

		// Use this if the array elements are text only
        listItem.textContent = listData[i];

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

        // Reset the list item
        listItem = document.createElement('li');
    }
}

// Usage
makeList();