0
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="top">surprise</div>
    <script>
        document.getElementsByClassName("top").style.color ="red";
    </script>
</body>

</html>

I don't know why this is not working, hoping to have a good explanation .

  • 2
    `getElementsByClassName` will return a nodelist, as its plural. You could use `querySelector` instead – marks Apr 27 '21 at 16:04
  • 2
    `getElementsByClassName` returns an array of elements. You want `getElementsByClassName('top')[0]` or `querySelector('.top')`. You should also get in the habit of adding `console.log` calls to parts of your code to help debug the return values from functions. – Andy Ray Apr 27 '21 at 16:04
  • Since it returns a collection of elements (get**Elements**ByClassName), you'll have to mention the index of element you want to access. `getElementsByClassName('top')[0]` – Shahzaib Ahmed Apr 27 '21 at 16:14

1 Answers1

0

You need to access style property on element. document.getElementsByClassName("top") will return you an HTMLCollection.

you need to update your script:

document.getElementsByClassName("top")[0].style.color ="red";

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="top">surprise</div>
    <script>
        document.getElementsByClassName("top")[0].style.color ="red";
    </script>
</body>

</html>
Punith Mithra
  • 608
  • 5
  • 9