Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct syntax to point at multiple elements in a JavaScript Array?

<body>

<p class="initial">Number One!</p>
<p class="initial">Number Two!</p>
<p class="initial">Number Three!</p>

<script>
var x = document.getElementsByClassName("initial");
x[0].innerHTML = "<span class=\"fix\">super duper</span>";
</script>

</body>

x[0].innerHTML points to the first element. However what if I wanted to change the innerHTML of several elements in the array? For instance the first and the third. x[0, 2].innerHTML doesn't work. I've been looking for the syntax online and I can't find anything.

like image 488
DR01D Avatar asked Dec 11 '25 05:12

DR01D


2 Answers

Consider a for loop to run the code multiple times:

for (var i = 0; i < 3; i++) {
    x[i].innerHTML = "<span class=\"fix\">super duper</span>";
}

If there are particular elements you want, create an array and iterate through with a forEach loop:

var desiredElems = [1, 3, 7, 9];
desiredElems.forEach(function(element) {
    x[element].innerHTML = "<span class=\"fix\">super duper</span>";
});
like image 125
Aurora0001 Avatar answered Dec 13 '25 17:12

Aurora0001


Assignments are expressions that return the assigned value, so you can do the following:

var x = document.getElementsByClassName("initial");
x[0].innerHTML = x[2].innerHTML = "<span class=\"fix\">super duper</span>";
<p class="initial">Number One!</p>
<p class="initial">Number Two!</p>
<p class="initial">Number Three!</p>

If you want to change more than a handful indices, you could define the indices as an array and use a loop:

var indices = [0, 2];

var x = document.getElementsByClassName("initial");
indices.forEach(function(i) {
  x[i].innerHTML = "<span class=\"fix\">super duper</span>";
})
<p class="initial">Number One!</p>
<p class="initial">Number Two!</p>
<p class="initial">Number Three!</p>
like image 21
TimoStaudinger Avatar answered Dec 13 '25 18:12

TimoStaudinger