13

I can't figure out how to use multiple IDs in JavaScript. No problem with single ID and getElementById, but as soon as I change IDs to class and try using getElementsByClassName the function stops working. I've read about a 100 post about the topic; still haven't found the answer, so I hope someone here knows how to make getElementsByClassName work.

Here's some simple code that I have used for testing:

function change(){
    document.getElementById('box_one').style.backgroundColor = "blue";
}

function change_boxes(){
    document.getElementsByClassName ('boxes').style.backgroundColor = "green";
}

   
<input name="" type="button" onClick="change(document.getElementById('box_one')); change_boxes(document.getElementsByClassName('boxes'))" value="Click" />   

<div id="box_one"></div>
<div class="boxes" ></div>
<div class="boxes" ></div>
4

3 Answers 3

29

getElementsByClassName() returns a nodeList HTMLCollection*. You are trying to operate directly on the result; you need to iterate through the results.

function change_boxes() {
    var boxes = document.getElementsByClassName('boxes'),
        i = boxes.length;

    while(i--) {
        boxes[i].style.backgroundColor = "green";
    }
}

* updated to reflect change in interface

Sign up to request clarification or add additional context in comments.

5 Comments

Thx - working fine. Not sure i actually understand why - ill copy your solution into the larger project im working on and hopefully i can make it work there as well
@Kenneth: getElementsByClassName returns all elements with that class name, i.e. multiple elements. To change properties of these elements you have to iterate over the list of elements.
Hmm - got another problem i cant figure out. I have 20 buttons on same page using same styling. Buttons are div-class and selected by onClick with the working code from Mathletics. Each button is actually made out of 2 buttons which changes position by z-index when clicked and presents a new picture for every button.
perfect, just what we needed. something to keep in mind, if changing the className inside a loop that uses getElementsByClassName, you need to work backwards (like the example above, i--). thanks!
It actually returns an instance of a HTMLCollection now instead of NodeList
4

getElementsByClassName Returns a set of elements which have all the given class names

var elements = document.getElementsByClassName('boxes');
for(var i=0, l=elements.length; i<l; i++){
 elements[i].style.backgroundColor = "green";
}

Comments

-1

getElementsByClassName returns a list of elements so you would need to iterate through them and set the styles on each item one by one. It also has limited support in IE, so you might be better off using jQuery:

$(".boxes").css("backgroundColor", "green");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.