0

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

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

One last question, is there a way to combine elements and a var? So $(somevar, '#one').css....?
@user2413333 yes, what is somevar? is it a part of the id or some other id? then $(somevar + ", #one").css
somevar is just an example for a cached element in a var, so var somevar = $('#element');
0

You can use class selector.

$('.myclass').css('color', newColor );

or

$('#one, #two, #three, #four, #five, #etc').css('color', newColor );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.