I'm currently making a game, and I'm trying to change the CSS values of a whole class of objects. For a single ID, I would use, document.getElementById("idHere")
, but I need something like document.getElementByClass("classHere")
. Thanks!
I'm currently making a game, and I'm trying to change the CSS values of a whole class of objects. For a single ID, I would use, document.getElementById("idHere")
, but I need something like document.getElementByClass("classHere")
. Thanks!
6 Answers
Reset to default 6There is simply document.getElementsByClassName("myClass")
, which returns an array of all the elements with that HTML class.
If you're using jQuery, you can do it with $(".myClass")
, which will return a collection of all of the elements with that class.
There exists getElementsByClassName
; see document.getElementsByClassName
on MDN.
If you can use JQuery I suggest $('.classHere').
Two ways to do it:
document.getElementsByClassName("theClassName");
document.querySelectorAll(".theClassName");
These methods won't work on older browsers (like IE7 or IE8). In this case you'll have to iterate through elements to check the class name, or rely on a library like jQuery.
If you can't or don't want to use jQuery, do the following:
function changeClassName(className, newClassName) {
var elements = document.getElementsByClassName(className);
for (var i = 0; i < elements; ++i) {
var item = elements[i];
item.className = newClassName;
}
}
If you decide to use jQuery:
function changeClassName(className, newClassName) {
$('.'+className).toggleClass(newClassName);
}
If you need to change CSS values according to class name you can just use:
document.getElementsByClassName("classname");
this will return you an array of all elements in whole document that have class which you search.
This will allow you to write a loop to change CSS for all of returned elements.