4

Is it possible to alter css class with jQuery? For instance if i have this class defined:

.my-class{
  right:10px;     
}

and now I want to change it to

.my-class{
  right:20px;     
}

without having to select all the elements of this class with $(".myClass"). The reason i want to do this is that i am adding a lot of elements at run time in js and it would be nice to swap the class definition ahead of time.

.myClass is defined in css file, otherwise i suppose i could have changed its definition with jsf/jstl had it been on the page.

1

3 Answers 3

3

Technically you can edit stylesheets with Javascript using the document.styleSheets object but you might find it a lot more work than it's worth. Read this article to get an idea of what a mess it is: http://www.quirksmode.org/dom/changess.html

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

1 Comment

Yeah, it's a shame that it's such a mess. It could be useful.
1

If I was doing this I would do it with inline styles.

<div style="right:20px"><!-- blank --></div>

$('div').css('right','10px');

The other option is to have two classes and toggle between them using toggleClass()

<div class="right10"><!-- blank --></div>

$('div').toggleClass('right20');

3 Comments

I would say the same thing. If the styling is too variable, I'd go inline, if there are a set number of options, I would possibly define and toggle them.
There are only two variations of the class, which makes it simpler. But i would prefer not to query the dom for these elements. The page i'm rendering is huge.
Your selectors can be made more specific to speed things up.
1

Add a second class and set the elements to be the second class when you add them? Alternatively you can swap out style sheets at runtime.

http://www.kelvinluck.com/2006/05/switch-stylesheets-with-jquery/

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.