19

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>

7 Answers 7

27

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>

Sign up to request clarification or add additional context in comments.

7 Comments

Yeah but I want to add lists in <div class ="box"><ul></ul></div>. How can I do that?
Oh I just change <ul></ul> to <div></div>. Your solution did not have to createElement. What I use it how to do that?
Hi - I am not sure as to the structure you want to have - but when using this string based approach - its as easy as adding the element into the string. To demonstrate - I changed the empty element in the page into a div and added the <ul> and </ul> to the string in the js and voila - you have a div with a ul inside of it.
Okay - Thank you for your help. This is an easy/simple solution.
This is truely amazing. I mean I have done this multiple times in angular and react projects but never in javascript alone...
|
9

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:
    1. Create a new <li>
    2. Create a text node with the text from the array
    3. Append the text to the <li>
    4. 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.

2 Comments

I had this before I posted here but it did not work. Can you point what was wrong? ``` 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); } } ```
First of all, if you have already written code in an attempt to solve your problem it is recommended that you include it in your post, and we will help you debug it. As for why it doesn't work, all you're doing is appending empty <li> nodes. At no point do you give them any content. You assign items from the array to the list variable, but then on the very next line you overwrite it and turn it into an empty <li> instead.
7

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

2 Comments

I do not know much ES6. What ${item} means?
It is a template literal string, see the link in my answer for more information.
4

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>

Comments

0

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>

Comments

0

So your class box was missing the . inside the parenthesis. Should look something more like this

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>

Comments

-1

You also could do a mapping for the list items.

const slides = ["slide 1", "slide 2", "slide 3", "slide 4", "slide 5"];

and then in your html

<ul>
    {slides.map((slide) => (
        <li>{slide}</li>
    ))}
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.