Marcin Misiak Marcin Misiak - 3 months ago 28
Javascript Question

Javascript li list from array with for loop

I want to make

li
elements with properties like below but it doesn't work at all. Could you help me with what is wrong?

var array = [1, 2, 3, "mm", "b", "c", "mm", "y", "mm"];
var list = document.getElementById("list");

function addText(array) {
for (var i = 0; i <= array.length; i++); {
var text = array[i];
if (array[i] == "mm") {
var listItem = document.createElement("LI");
listItem.innerHTML = text;
list.appendChild(listItem);
}
}
};

Answer

The semicolon at the end of the for loop is the problem.

for (var i = 0; i <= array.length; i++); // <-- remove this

The semicolon makes the loop do nothing for array.length + 1 times instead of looping through the code in between the braces. You also want to change the <= to < so that you don't exceed the array boundary. Arrays are zero based, so your array of 9 items have indices from 0-8. You can also just compare text instead since you're copying it to a variable (not sure what was your intent since you can just get rid of the temporary outright).

Also, since you're just adding text, use textContent over innerHTML

Demo:

var array = [1, 2, 3, "mm", "b", "c", "mm", "y", "mm"];
var list = document.getElementById("list");

function addText(array) {
  for (var i = 0; i < array.length; i++) {
    var text = array[i];
    if (text == "mm") {
      var listItem = document.createElement("LI");
      listItem.textContent = text;
      list.appendChild(listItem);
    }
  }
}

addText(array);
<ul id="list">
</ul>

Comments