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

1

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

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

When I use document.getElementsByClassName("life").innerText = "outrovalor" nothing happens. In the console apparently it worked, but in the page the information does not change. Is this due to the fact that it was created in php? Can you work around this problem?

    
asked by anonymous 02.06.2016 / 15:48

1 answer

1

document.getElementsByClassName(...) returns an array (vector) of all elements with the class. Here's how:

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

So we selected only the first one, which I assume to be 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>
    
02.06.2016 / 15:56