Why is getElementsByClassName not working?

Asked

Viewed 47 times

1

I have to make a program that when clicking on the link "HIGH CONTRAST" the whole background turns black and the color of the letter turns white

My question is what am I doing wrong? If I exchange all classes for Id s only works on the first line (which is expected), then why does using classes not take the three lines?

<!DOCTYPE html>
    <html lang="pt-br">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script>
            function Contraste(){
                document.getElementsByClassName ('abc').style.cssText = 'background-color: black ; color : white ;'
            }
        </script>
    </head>
    <body>
        <h2 class="abc" style="color: red;">Olá</h2>
        <h2 class="abc" style="color:blue;">Tudo bem</h2>
        <h2 class="abc" style="color: green;">Com você?</h2>

        <a href="#"  
        onclick ="Contraste()">ALTO CONTRASTE
        </a>
    </body>
</html> 
  • 1

    The method Document.getElementsByClassName() returns an object array where you must iterate to work with individual elements.

  • But do you think if I keep going down the path of using it and then iterate it works? Or is there another simpler way?

1 answer

3


As said in the comments the method Document.getElementsByClassName() returns an object array where you must iterate to work with individual elements.

In javascript there are several ways to iterate in this case I used the loop for..of

function Contraste() {
  for (let e of document.getElementsByClassName('abc')) {
    e.style.cssText = 'background-color: black ; color : white ;'
  }
}
<!DOCTYPE html>
<html lang="pt-br">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

</head>

<body>
  <h2 class="abc" style="color: red;">Olá</h2>
  <h2 class="abc" style="color:blue;">Tudo bem</h2>
  <h2 class="abc" style="color: green;">Com você?</h2>

  <a href="#" onclick="Contraste()">ALTO CONTRASTE
        </a>
</body>

</html>

Browser other questions tagged

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