Skip to content
Related Articles

Related Articles

How to create HTML list from JavaScript array ?
  • Last Updated : 10 Mar, 2021

In this article, we will be creating an HTML list from a JavaScript array. This is needed sometimes when we fetch JSON from any source and displaying the data into the frontend and in many other cases also. 

Problem statement: Display the array [‘Ram’, ‘Shyam’, ‘Sita’, ‘Gita’ ] into an HTML list.

To achieve this, we will follow the steps below.

  • Step 1: Create the HTML skeleton.

    HTML






    <!DOCTYPE html>
    <html>
      <head> </head>
      <body>
        <center><h1>GeeksforGeeks</h1></center>
        <ul id="myList"></ul>
      </body>
    </html>
  • Step 2: Create a variable named list and get the element whose id is “myList”.

    Javascript




    let list = document.getElementById("myList");
  • Step 3: Now iterate all the array items using JavaScript forEach and at each iteration, create a li element and put the innerText value the same as the current item, and append the li at the list.

    Javascript




    let data = ['Ram', 'Shyam', 'Sita', 'Gita' ];
      
    let list = document.getElementById("myList");
      
    data.forEach((item)=>{
      let li = document.createElement("li");
      li.innerText = item;
      list.appendChild(li);
    })

Complete code:

HTML




<!DOCTYPE html>
<html>
  <head> </head>
  <body>
    <center><h1>GeeksforGeeks</h1></center>
    <ul id="myList"></ul>
    <script>
      let data = ["Ram", "Shyam", "Sita", "Gita"];
  
      let list = document.getElementById("myList");
  
      data.forEach((item) => {
        let li = document.createElement("li");
        li.innerText = item;
        list.appendChild(li);
      });
    </script>
  </body>
</html>

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :