1

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

2
  • 1
    headone is not an array its and html element <h1>Hello World</h1> You are trying to loop through an html element Commented Nov 14, 2021 at 4:57
  • I am trying to loop the h1 10 times. I can't figure out how though. Commented Nov 15, 2021 at 7:19

2 Answers 2

2

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

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

2 Comments

I don't need to access each letter, I need to loop the h1 10 times but in an ordered list.
@JLB Do you mean you want the content of h1 to be added to a list 10 times?
2

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.