Create ul and li elements dynamically using JavaScript

← PrevNext →

HTML <ul> and <li> elements are often used to show a list of items with bullet points on a web page. You can add these elements at design time and dynamically at run time. I’ll show you how you can create <ul> and <li> elements dynamically using JavaScript.

Create Dynamic ul and li element using JavaScript

You may also like: Create HTML ul and li elements using XML data in jQuery

Let’s see an example.

The Markup and Script

In the markup section, I have a <div> element, which will serve as a container and here I’ll append the dynamically created list items to it.

<!DOCTYPE html>
<html>
<body>
    <!--The container where I'll add the dynamic ul and li elements.-->
    <div id='container'></div>
</body>
<script>
    var arr = ['alpha', 'bravo', 'charlie', 'delta', 'echo'];
    var cont = document.getElementById('container');

    // create ul element and set the attributes.
    var ul = document.createElement('ul');
    ul.setAttribute('style', 'padding: 0; margin: 0;');
    ul.setAttribute('id', 'theList');

    for (i = 0; i <= arr.length - 1; i++) {
        var li = document.createElement('li');     // create li element.
        li.innerHTML = arr[i];      // assigning text to li using array value.
        li.setAttribute('style', 'display: block;');    // remove the bullets.

        ul.appendChild(li);     // append li to ul.
    }

    cont.appendChild(ul);       // add list to the container.
</script>
</html>
Try it

In addition, you can do this more dynamically using jQuery. Check this article.

Using ES6 Features

If you are using ES6, the script should be,

<script>
    const arr = ['alpha', 'bravo', 'charlie', 'delta', 'echo'];
    const cont = document.getElementById('container');

    // create ul element and set its attributes.
    const ul = document.createElement('ul');
    ul.setAttribute ('style', 'padding: 0; margin: 0;');
    ul.setAttribute('id', 'theList');

    for (i = 0; i <= arr.length - 1; i++) {
        const li = document.createElement('li');	// create li element.
        
        li.innerHTML = arr[i];	                        // assigning text to li using array value.
        li.setAttribute ('style', 'display: block;');	// remove the bullets.

        ul.appendChild(li);		// append li to ul.
    }
    cont.appendChild(ul);		// add ul to the container.
</script>

You can also do this using jQuery. I personally prefer the JavaScript and I have explained it in the above example. Using the createElement() method, you can easily create any DOM element dynamically.

Well, that’s it. Thanks for reading.

← PreviousNext →