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 »
- 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>
- We have an array with five items.
let array = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5'];
- 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'); }
- 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 »
Pdf
Save
Listen
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] Create li from array using loop. In the first example, you will le…
asked
Apu
0 answers
2915
In this article, we are going to create unordered list from a javascript array. [1] Creat…
Answer Link
answered
Apu