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>
The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection.
The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.
getElementsByClassName("a") will reliably list them in order: d1, d2, d3, d4, d5.
getElementById() is used to access the DOM elements using their id and getElementsByClassName() is used to access element(s) using their class .
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
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With