Create li from loop through array and display to HTML as a list

In this article, we are going to create unordered list from a javascript array.


In the first example, you will learn How to dynamically create ul and li elements by for loop in JavaScript.
  1. Create an ul tag with an id attribute.
  2. Create a for loop and inside the for loop, create a li element using the createElement() method.
  3. Set the li value from the array using the innerText property and append the created li at the bottom of the ul as a child.
Example using for loop
  let array = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5'];
  for (let i = 0; i < array.length; i++){
    let list = document.createElement('li');
    list.innerText=array[i];
      document.querySelector('.box').appendChild(list);
}
Try it Yourself »
Example using forEach() method
  let array = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5'];

  array.forEach(function(item) {
  let list = document.createElement("li");
  list.innerText = item;
       document.querySelector('.box').appendChild(list);
    })
Try it Yourself »