Home > Back-end >  Having issues creating a for loop for a list created in JS
Having issues creating a for loop for a list created in JS

Time:11-14

I'm trying to for loop the H1 object through a list 10 times. I'm not sure where I went wrong any help would be appreciated.

var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);

var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);

var helloWorld = document.getElementById("OLJS");
 
for (var i = 0; headOne < 10; i  );{
        var listItems = document.createElement("li");
        listItems.innerHTML = headOne[i];
        helloWorld.append(listItems);

}

CodePudding user response:

If you want to loop 10 times then do:

for (let i = 0; i < 10; i  ) {
  // Do something
}

And in your case if you are trying to access each letter of headOne element and append it to the helloWorld list then you can do the following:

for (let i = 0; i < headOne.textContent.length; i  ) {
  let listItems = document.createElement('li')
  listItems.textContent = headOne.textContent[i]
  helloWorld.append(listItems)
}

You might also want to read more about Loops and iteration

CodePudding user response:

var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);

var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);

//var helloWorld = document.getElementById("OLJS");

for (var i = 0; i < 10; i  ) {
  var listItems = document.createElement("li");
  listItems.innerHTML = "order list item "   (i   1);
  newOrderedList.append(listItems);
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related