Reputation: 1405
I have a series of elements (over 20) that all need a color that the user enters. Using PHP + CSS I end up with this output:
#one, #two, #three, #four, #five, #etc { color: #222; }
It works fine, but I now need to edit that color after the DOM has loaded using jQuery/Javascript. Again, it will be user entry so the color could be anything.
Is there a quick way to apply the changes to all the elements at once? Or do I have to do the following?
$('#one').css('color', newColor );
$('#two').css('color', newColor );
.... etc
I am hoping there is a way, because like I mentioned, there are over 20 elements that need this change. Thanks guys
Upvotes: 0
Views: 967
Reputation: 123739
You can do:
$('#one, #two, #three, #four, #five, #etc').css('color', newColor );
But if you have a common class assigned to them, it makes it more easier.
$('.commonCls').css('color', newColor );
Or if these elements are say div
(and are the only elements) and inside a container container
then you could just do.
$('.container').find('div').css('color', newColor);
and better if you know the color in advance, just add a cssrule for a classname and add that class to these elements, which will help more in cascading than specifying inline color (which css()
does).
$('.commonCls').addClass(newClass);
to add on, if you have to use id and if your ids have a common part to it. ex: #one-Section, #two-Section etc..
then you can use attribute endswith selector ($), You have contains (*) and startswith (^) selector as well.
$('[id$="Section"]').addClass(newClass); //or .css
Upvotes: 6
Reputation: 6180
You can use class selector.
$('.myclass').css('color', newColor );
or
$('#one, #two, #three, #four, #five, #etc').css('color', newColor );
Upvotes: 0