Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get actual value specified in CSS using jQuery [duplicate]

Explanation

I cannot believe this has not been asked before but anyway... Please do not get confused with this question.

I am trying to store the height of an element using the jQuery data method so that I can retrieve this value and reset the original value on a specific element.

However, when I try to get the height of my element, it returns the computed height and not the actual CSS value. Whilst this is extremely helpful in other cases, I actually need to get the exact value specified in my stylesheet whether it be 100%, auto, 10px etc...

My Question

Is there a way to get the exact CSS (non-computed) value of an element using jQuery?

For example (CSS):

#wrapper {
    height: auto;
}

And JS:

// Returns 'auto' NOT computed value...
var height = $('#wrapper').height();

Further Information

The only alternative I can currently see is just removing the inline style tag on my element which will remove any styles applied by jQuery. The obviously flaw in this method is that it will remove all styles not just one in particular...

like image 222
Ben Carey Avatar asked Oct 16 '13 13:10

Ben Carey


2 Answers

Using jQuery you can only get the calculated value.

As an alternative, I have written a script to find the original css value by enumerating the stylesheets applied to the page, matching the selector and weighing it up by precedence and CSS specificity.

This is handy for finding out if something is auto vs. 100% vs. fixed size.

usage :

resolveAppliedStyle(document.getElementById("wrapper"), "height");

You can get the script for resolveAppliedStyle from :

https://github.com/stephen-james/FixedHeaderTable/blob/master/dependencies/lib/resolveAppliedStyle.js

and the script it uses to calculate specificity from :

https://github.com/keeganstreet/specificity/blob/master/specificity.js

like image 171
Stephen James Avatar answered Oct 06 '22 01:10

Stephen James


Is there a way to get the exact CSS (non-computed) value of an element using jQuery?

You can only retrieve the computed value in px via the DOM.

That being said, you can work out the percentage by getting the elements height and comparing it to the parent's height. em, en and other measurements are not possible.

like image 25
Rory McCrossan Avatar answered Oct 06 '22 01:10

Rory McCrossan