Dwarf Vader
Dwarf Vader

Reputation: 429

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();.

Upvotes: 2

Views: 4617

Answers (2)

Quentin
Quentin

Reputation: 943569

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.

Upvotes: 8

The.Anti.9
The.Anti.9

Reputation: 44648

You should try using a library like jQuery that allows you to use CSS selectors. Then you would be able to do

$('.a,.A').css("background", "#f00");

You could even change multiple styles at once with multiple elements

$('.a,.A').css({"background": "#f00", "color": "#000"});

Upvotes: 2

Related Questions