I am learning javaScript and I want to loop array and display to HTML as a list. How can I do that?
Array:
var array = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5', 'Slide 6', 'Slide 7', 'Slide 8', 'Slide 9'];
javascript:
function listItem(item){
for (var i = 0; i < item.array.length; i++){
var list = item.array[i];
list = document.createElement('li');
document.getElementByClass('box').appendChild(list);
console.log(list);
}
}
<div class ="box"><ul></ul></div>
Whilst all the supplied answers work and are fine - they all suffer from the same issue - in that they append the element to the DOM with each iteration. With a small list this will not be an issue, but if you are dealing with a large number of elements that you want in your list - the constant manipulation of hte DOM will have a performance cost.
It is far better (IMO) to build a single string of the li's and then when the array is fully iterated through - pass the string to the UL using .innerHTML - in the DOM in a single action. Same result - but faster.
var slides = ["slide 1", "slide 2", "slide 3", "slide 4", "slide 5"]
var str = '<ul>'
slides.forEach(function(slide) {
str += '<li>'+ slide + '</li>';
});
str += '</ul>';
document.getElementById("slideContainer").innerHTML = str;
<div id="slideContainer"></div>
Fairly simple:
var array = ["slide 1", "slide 2", "slide 3", "slide 4", "slide 5"]
array.forEach(function(item) {
var li = document.createElement("li");
var text = document.createTextNode(item);
li.appendChild(text);
document.getElementById("myUl").appendChild(li);
});
<ul id="myUl"></ul>
This code does the following:
- For each item of the array:
- Create a new
<li>
- Create a text node with the text from the array
- Append the text to the
<li>
- Append the
<li>
to the <ul>
This all becomes much simpler if you use jQuery:
var array = ["slide 1", "slide 2", "slide 3", "slide 4", "slide 5"];
array.forEach(function(item) {
$("#myUL").append("<li>" + item + "</li>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myUL">
</ul>
EDIT: If you want to use a normal for loop instead of forEach, you can do like so:
var array = ["slide 1", "slide 2", "slide 3", "slide 4", "slide 5"];
for (i = 0; i < array.length; i++) {
var li = document.createElement("li");
var text = document.createTextNode(array[i]);
li.appendChild(text);
document.getElementById("myUl").appendChild(li);
}
<ul id="myUl"></ul>
The only difference in this code is that instead of using the built-in forEach method to loop through the array and perform operations on each element, we instead manually loop through the indices of the array.
You could use the ES6 method reduce and template literals. You could use them like this:
var array = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5', 'Slide 6', 'Slide 7', 'Slide 8', 'Slide 9'],
// Reduce will iterate over all the array items and returns a single value.
listItems = array.reduce((result, item) => {
// Add a string to the result for the current item. This syntax is using template literals.
result += `<li>${item}</li>`;
// Always return the result in the reduce callback, it will be the value or result in the next iteration.
return result;
}, ''); // The '' is an empty string, it is the initial value result.
// Get the element from the DOM in which to display the list, this should be an ul or ol element.
resultElement = document.getElementById('result');
// Set the inner HTML
resultElement.innerHTML = listItems;
<ul id="result"></ul>
For more information on reduce see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce. And if you want to know more about template literals check here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Convert the array into a string by using Array#join and using list item tags as separators. Add the start and end tag manually using string concatenation (+
). Assign the string to the list element (ul#target
) using Element#innerHTML:
var array = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5', 'Slide 6', 'Slide 7', 'Slide 8', 'Slide 9'];
target.innerHTML = '<li>' + array.join('</li><li>') + '</li>';
<ul id="target"></ul>
Try this ,also you can add to the list
var arr = [
Math.random().toFixed(2),
Math.random().toFixed(2),
Math.random().toFixed(2),
Math.random().toFixed(2),
Math.random().toFixed(2)
];
console.log(arr);
var ul = document.createElement('ul');
ul.className = 'myUL';
document.getElementById('container').appendChild(ul);
function myFunction() {
// for(var i =0;i<5;i++){
// arr.push(Math.random().toFixed(2));
// }
create(arr);
}
function create(arr){
arr.forEach(function(data){
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML += data;
li.className = "myList";
});
}create(arr);
#container .myUL{
padding:0px;
}
#container .myUL .myList {
list-style-type: none;
border:1px solid grey;
padding:5%;
border-radius:5px;
margin:4px;
}
.click{
width:80px;
height:30px;
border-radius:5px;
color:#fff;
background:#323232;
font-size:15px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<!-- create a ul li using js -->
<button class="click" onclick="myFunction()">Click Me</button>
<div id="container"></div>
</body>
</html>