Click here to Skip to main content
14,929,666 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Why it doesn't works? Where mistakes?

HTML
<body onload = "go()">
  <div class = "elem"></div>
  <button onclick = "go()">click to change bgcolor</button>
</body>


JavaScript
document.getElementsByClassName("elem").style.backgroundColor = "red";


CSS
div {
  width: 100px;
  height: 100px;
  border: 2px solid black;
}


What I have tried:

Please explain me what wrong in this code. Every time when I write code at first glance all right but when I run code always something wrong, and I don't now what wrong. I'm desperate.
Posted
Updated 30-Oct-17 9:07am

"The getElementsByClassName() method returns a collection of an element's child elements with the specified class name, as a NodeList object." That said, the JavaScript syntax should look like below, assuming there only ONE element with class name "elem"

JavaScript
document.getElementsByClassName("elem")[0].style.backgroundColor = "red";

Example: CP_ChangeBgColor - JSFiddle[^]

Reference:
HTML DOM getElementsByClassName() Method[^]
   
Comments
Karthik_Mahalingam 31-Oct-17 1:42am
   
5 its always better to validate the index of the collection.
Bryian Tan 31-Oct-17 2:08am
   
Thanks :). Yes. I agreed.
getElementsByClassName returns an array so you have to go through the elements one by one and set the style.

var els = document.getElementsByClassName("content-button");

for (var i = 0; i < els.length; i++)
{
    els[i].style.backgroundColor = "red";
}
   
Comments
Karthik_Mahalingam 31-Oct-17 1:43am
   
5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900