tags:

views:

48

answers:

3

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  A: 

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');
DavidYell
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.
tjko
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.
Yev
Your selectors can be made more specific to speed things up.
DavidYell
+1  A: 

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/

Jonathan Park
+3  A: 

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

edeverett
Yuk, you are right, that's an awful approach.
Yev
Yeah, it's a shame that it's such a mess. It could be useful.
edeverett