In this article, we will learn how to create an HTML list from a JavaScript array. An array can be converted into a list by iterating over its elements and creating <li> elements dynamically.
Approach 1: Using for loop
In this approach, we use a for loop to iterate through the array. For each element, we create an <li> element and append it to the <ul> element.
Example: In this example, we create an HTML list dynamically from a JavaScript array using a for loop.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create HTML List</title>
</head>
<body>
<ul id="myList"></ul>
<script>
const data = ["Ryan", "Sam", "Lucas", "Gorge"];
const list = document.getElementById("myList");
for (let i = 0; i < data.length; i++) {
const li = document.createElement("li");
li.innerText = data[i];
list.appendChild(li);
}
</script>
</body>
</html>
Approach 2: Using forEach() Method
In this approach, we use the forEach() method to iterate over each element of the array. For every element, an <li> element is created and added to the list.
Example: In this example, we use the forEach() method to create an HTML list from the array elements.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create HTML List</title>
</head>
<body>
<ul id="myList"></ul>
<script>
const data = ["Ryan", "Sam", "Lucas", "Gorge"];
const list = document.getElementById("myList");
data.forEach((item) => {
const li = document.createElement("li");
li.innerText = item;
list.appendChild(li);
});
</script>
</body>
</html>
Approach 3: Using join() Method
In this approach, we use map() to convert each array element into an <li> element and join() to combine them into a single HTML string. The resulting string is then assigned to innerHTML.
Example: In this example, we create an HTML list by combining the array elements into an HTML string using map() and join().
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create HTML List</title>
</head>
<body>
<ul id="myList"></ul>
<script>
const data = ["Ryan", "Sam", "Lucas", "Gorge"];
const list = document.getElementById("myList");
list.innerHTML = data
.map(item => `<li>${item}</li>`)
.join("");
</script>
</body>
</html>