-1

I recently starting learning JS and for some reason I cannot get getElementByClassName to work for me. Here's my code.

//variable to store the ID h1
var id = document.getElementById("first");
//variable to store the class h1
var cs = document.getElementsByClassName("second");

//coloring the id 'first'
id.style.color = "red";

cs.style.color = "blue";
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test Site</title>
  </head>
  <body>
    <h1 id="first">This is an ID</h1>
    <h1 class="second">This is a class</h2>

    <script src="index.js"></script>
  </body>
</html>

The element with an ID is changing color but the one with a class isn't. Any help would be greatly appreciated.

Tyler Polito
  • 23
  • 1
  • 6

1 Answers1

1

getElementById returns one single element as you should not have multiple element with the same Id in the DOM.

getElementsByClassName returns an HTMLCollection as many elements can share the same class name.

try this instead :

//variable to store the ID h1
var id = document.getElementById("first");
//variable to store the class h1
var cs = document.getElementsByClassName("second");

//coloring the id 'first'
id.style.color = "red";

cs[0].style.color = "blue";

In real life use case you might wanna loop through the array.

M. Gara
  • 809
  • 12
  • 26