getElementsByClassName works to change css?

Asked

Viewed 214 times

0

I’m trying to make a change in css by clicking on the word but when I use Getelementsbyclassname nothing happens, but with the ID I can do this, however as several elements will have exactly the same property, I would rather not with ID

This is the code

   <script>
    function ganha(){
        document.getElementsByClassName("winner").style.color = "green";
    }


    </script>

    <div class="winner" onclick="ganha()" >
      Snut
    </div>
  • Read it here: https://answall.com/questions/228670/document-getelementsbyclassname-elements-com-mais-de-umarclass

1 answer

0

Let’s assume that there are 10 div elements with the class "example"

...

when you call the Document.getElementsByClassName("Winner") method it returns you an array of elements, so you can pass them inside a loop (for) and set them all, the way you are doing it won’t work at all, follow an example

window.onload = function() {
	var elementos = document.getElementsByClassName('exemplo');
  
  elementos[2].style.color = "#ff0";
  
  for(var i = 0; i < elementos.length; i++) {
  	elementos[i].style.color = "red";
  }
};
<div class="exemplo">
 e1
</div>
<div class="exemplo">
 e2
</div>
<div class="exemplo">
 e3
</div>
<div class="exemplo">
 e4
</div>

Browser other questions tagged

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