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.

Elijah
  • 1,252
  • 3
  • 21
  • 32
  • Duplicate: http://stackoverflow.com/questions/622122/how-can-i-change-the-css-class-rules-using-jquery – spinon Jul 28 '10 at 16:29

3 Answers3

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

edeverett
  • 8,012
  • 33
  • 28
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');
David Yell
  • 11,756
  • 13
  • 61
  • 100
  • 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. – TJ Koblentz Jul 28 '10 at 16:30
  • 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. – Elijah Jul 28 '10 at 18:05
  • Your selectors can be made more specific to speed things up. – David Yell Jul 29 '10 at 09:02
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/

Jonathan Park
  • 775
  • 5
  • 12