开发者

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

开发者 https://www.devze.com 2023-04-12 08:50 出处:网络
I have a bunch of divs with different combinations of classes in each (e.g. \"a A\", \"a b\", \"b A\", \"b\" etc.).

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


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.


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"});
0

精彩评论

暂无评论...
验证码 换一张
取 消