Skip to content
Related Articles
Open in App
Not now

Related Articles

How to create HTML list from JavaScript array ?

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 13 Dec, 2022
Improve Article
Save Article
Like Article

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 display the data in 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




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

Output:


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!