Justin808
Justin808

Reputation: 21512

How can I tell the value of of a class attribute via jquery?

I have an element with a class, the class has a set width. Later I change the width with $('#elm').width(100); now, even later, I want to go back to the original value. Is there a way to get what the original value is from the class definition itself rather than store a bunch of globals with the values I need.

Thanks, Justin

Upvotes: 2

Views: 91

Answers (4)

Mark Schultheiss
Mark Schultheiss

Reputation: 34158

You COULD use the .data() to store the original and then restore the original values from there rather than use global values - it associates them that way.

Upvotes: 2

Piskvor left the building
Piskvor left the building

Reputation: 92752

Not from the same element on which you've explicitly set the width through JS; but you could create a new element, give it the class and see what width it gets.

Example:

$('#elem').width(100);
alert($('#elem').width()); // this will return 100, no matter what width #elem was before
$('body').add('<div class="someclass" id="elem2"></div>');
alert($('#elem').width()); // this may return the width as assigned in CSS to .someclass

Upvotes: 0

Malabar Front
Malabar Front

Reputation: 633

I'd suggest nikc's answer, but you could always do $('#elm').removeAttr("style"); if you want to wipe any styles your scripts have added, and return them to the CSS values you've specified.

Really, though, you should be leaving the styling out of the code and just adding, removing and toggling various classes.

Upvotes: 1

nikc.org
nikc.org

Reputation: 16952

Why not declare the modified width to another class, which you can then toggle, instead of using explicit values in you javascript?

Upvotes: 3

Related Questions