2

Is it possible to change the style of a class via JavaScript without looping through existing elements which have that class applied to them? Since my page uses a lot of DHTML, this method would prove ineffective when creating elements.

I've searched and have only found the answers "no" and "loop", but I feel that the styleSheet object must be able to do something along these lines. If not, however, I will accept that, but first I want to ask here where people are most likely to know the final answer.

Thanks for all answers.

1
  • Can you define a different class, and add/remove it as necessary? Unfortunately you cannot modify CSS style declarations from JavaScript. Commented May 14, 2011 at 6:01

2 Answers 2

1

You can add style rules to your stylesheets dynamically:

IE: addRule
Others: insertRule

Sign up to request clarification or add additional context in comments.

2 Comments

That's useful. Is there a way to change properties of elements individually, or is this as close as it gets?
You can access, change and/or remove all the rules in a stylesheet, but you'll have to write browser-specific code, sadly. Look at document.styleSheets[0].rules and document.styleSheets[0].cssRules.
0

Use jQuery, with this one line:

 $('.className').css("attrib", "value");

It will change the value of all elements with class = className.

Refer: http://api.jquery.com/css/

3 Comments

I'd prefer not to use jQuery for learning purposes. Also, that seems that it'd only affect existing elements as the loop method would.
Indeed; in fact, this will loop under the hood.
It'd only affect existing elements... Did not get you there, some elaboration will be welcome.

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.