JLB
JLB

Reputation: 29

Having issues creating a for loop for a list created in JS

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);
}

Upvotes: 1

Views: 53

Answers (2)

anonymous
anonymous

Reputation: 228

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);
}

Upvotes: 2

aerial
aerial

Reputation: 1198

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

Upvotes: 2

Related Questions