How ToJavaScriptMake Web StoriesQuiz GeneratorFAQ Schema GeneratorTable Maker3schools TranslateMore Tools..
Apu
Apu 11/05/2022

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.

[1] Create li from array using loop.

In the first example, you will learn how to dynamically create ul and li elements by for loop in JavaScript.

Example: create li using for loop.
<div id="box"></div>
<script>
 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);
  }
 </script>
Try it Yourself »
  1. Create an <ul> element with an id attribute and set its value to box. So that, we can display the created <li> elements inside it.
    <ul id='box'></ul>
    
  2. We have an array with five items.
    let array = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5'];
  3. Create a for loop and inside the for loop, create a li element using the createElement() method.
    for(let i = 0; i < array.length; i++){
        let list = document.createElement('li');
      }
  4. 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.
    <div id="box"></div>
    <script>
      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);
      }
     </script>
    Try it Yourself »

[2] Create ul & li using forEach() method.

The forEach() method calls a function for each element of an array.

Example using forEach() method
<div id="box"></div>
<script>
 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);
  })
 </script>
Try it Yourself »
Share

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

0
In this article, we are going to create unordered list from a javascript array. [1] Creat…
asked
0 answers

Write an Answer

Related Posts
Write an answer
back