Elijah
Elijah

Reputation: 1322

jQuery, altering css class itself

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.

Upvotes: 4

Views: 520

Answers (3)

edeverett
edeverett

Reputation: 8218

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

Upvotes: 3

Jonathan Park
Jonathan Park

Reputation: 775

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/

Upvotes: 1

David Yell
David Yell

Reputation: 11855

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');

Upvotes: 1

Related Questions