Document.getElementsByClassName("x"). innerText is not working

Asked

Viewed 271 times

1

I’m trying to use the document.getElementsByClassName().innerText but it does not replace the text contained in the class.

This text comes from a php echo: echo "<div class=\"life\">$life/$maxlife</div>"; staying in html as: <div class="life">1000/6000</div>

when I use the document.getElementsByClassName("life").innerText = "outrovalor" nothing happens. On the console it apparently worked, but on the page the information doesn’t change. What if you give to the fact that it was created in php? There’s a way around that problem?

1 answer

1


document.getElementsByClassName(...) returns an array (array) of all elements with the class. Do so:

document.getElementsByClassName("life")[0].innerText = "outrovalor"

So we select only the first, which I assume is what you want.

EXAMPLE

document.getElementsByClassName("life")[0].innerText = "outro valor"
<div class="life">
valor original
</div>

If you want to change all elements with this class: EXAMPLE

eles = document.getElementsByClassName("life");
for(var i in eles) {
    document.getElementsByClassName("life")[i].innerText = "outro valor " +i;
}
<div class="life">
valor 0
</div>
<div class="life">
valor 1
</div>
<div class="life">
valor 2
</div>

  • Cool Miguel, that’s right! Thanks for the help :)

  • 1

    Glad you solved @Jacksonantunes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.