0

With the help of a loop, I want to add an element into my list items.

Thanks a bunch for any advice!

4
  • Are you adding a single element? What do you need the loop for? And where are you trying to add them / it? Commented Oct 7, 2020 at 17:07
  • I want to add it to every list item. This is just to practice using loops! Commented Oct 7, 2020 at 17:13
  • Into it how? What is the final code look like? Commented Oct 7, 2020 at 17:14
  • If items is your NodeList of <li> elements, then items[i] would refer to the specific <li> at that index. Commented Oct 7, 2020 at 17:14

1 Answer 1

2

It's a little hard to tell the context of your problem, but I think using a for...of loop would better meet your needs, as it works with each item of the list individually.

Try this:

let item = document.getElementsByTagName('li');

for (let i of item){
    i.innerHTML = `${i.innerText} <span class="credits">100 credits</span>`;
}

If you need something that specifically uses an index loop, try this:

let item = document.getElementsByTagName('li');

for (let i = 0; i < item.length; i++){
    item[i].innerHTML = `${item[i].innerText} <span class="credits">100 credits</span>`;
}
Sign up to request clarification or add additional context in comments.

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.