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>
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.