0

I'm trying to insert content based on class however it only works once, how can I make it work multiple times?

See example: .innerHTML only runs once and not on the next occurrences

window.onload = function(){ 
document.getElementsByClassName("0")[0].innerHTML = `text0`;
document.getElementsByClassName("1")[0].innerHTML = `text1`;
document.getElementsByClassName("2")[0].innerHTML = `text2`;
document.getElementsByClassName("3")[0].innerHTML = `text3`;
}
<div class="x 0"></div>
<div class="x 1"></div>
<div class="x 2"></div>
<div class="x 3"></div>
<div class="x 0"></div>
<div class="x 1"></div>
<div class="x 2"></div>
<div class="x 3"></div>
  • 1
    What do you think the `[0]` in that code does, hm? You need to _loop over_ all the elements `getElementsByClassName` returns, and set the innerHTML for each of them individually. – CBroe Apr 29 '20 at 11:21
  • For the record, class names beginning with a number are actually invalid. Class names should begin with a letter (upper or lower case), a hyphen `-`, or an underscore `_`. – Scoots Apr 29 '20 at 11:29

2 Answers2

3
document.querySelectorAll('.x').forEach((element, i) => {
  element.innerText = `text${i}`
})
-1
var elemList = document.getElementsByClassName("0");
for (let i = 0; i < elemList.length; i++) {
    elemList[i].innerHTML = "text0";
}

An do this with classes 1, 2, etc.

Zoldszemesostoros
  • 387
  • 1
  • 3
  • 15
  • I would never advise using the `var in Array` in JavaScript - [it can cause a number of issues](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – Scoots Apr 29 '20 at 11:28
  • I've reversed my vote in that case; absolutely fine answer now. – Scoots Apr 30 '20 at 09:42