Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing multiple elements' styles with a same class name at once with JavaScript?

I have a bunch of divs with different combinations of classes in each (e.g. "a A", "a b", "b A", "b" etc.).

With a press of a button, I need to change the styles of, for example, all elements which have the class A (not only 'A', but must include it. E.g. both "d A" and "A" would work)

I have tried

document.getElementsByClassName('a A').style.background = "#f00";

but it didn't work. The console says that it can't set a style for element 'undefined', so I guess it doesn't get what I need with getElementsByClassName();.

like image 434
Dwarf Vader Avatar asked Jun 21 '26 10:06

Dwarf Vader


1 Answers

The DOM methods that getElementsBySomething (plural), as opposed to ones which getElementBySomething return a NodeList, not an element. NodeLists are Array-like objects.

You have to loop over it and change each element in turn if you take that approach. Most libraries have shortcut methods to do that for you.

e.g. for YUI 3:

Y.all('.foo').setStyle('background', '#f00');

or jQuery

jQuery('.foo').css('background', '#f00');

An alternative approach would be to modify the stylesheet itself with JavaScript.

A third option would be to set up your changed styles in advance, using a descendent selector such as:

.foo { /* something */ }
body.bar .foo { /* something else */ }

And then

document.body.className += " bar";

to activate the alternative styling.

like image 182
Quentin Avatar answered Jun 22 '26 23:06

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!