<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.
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>";
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With