Get the element from which the CSS rule is inherited

In jQuery, we can easily get the CSS value for a given element using the css method:

 $('#myElement').css('line-height'); // eg '16px' 

Now, since this CSS value could be inherited from the parent element, is there a way to find out which element this rule applies to?

For example, let's say I have the following HTML:

 <div class="parent"> <div id="myElement"></div> </div> 

and the following CSS:

 .parent { line-height: 20px; } 

Calling the css method on #myElement will return 20px , but it will not indicate that it was inherited from .parent .

I know that I can just launch Web Inspector / Dev Tools / Firebug , but I want to get it programmatically.

Is it possible?

+4
source share
2 answers

Move the parentElement chain by checking the css () value of each element. The first element with a value of parent (). Css (), which differs (possibly) in the element by which the CSS rule selector was selected.

See this script for an example: http://jsfiddle.net/broofa/VPWV9/2/ (see console.log output)

(Note. There are almost certainly complex cases where this will not work as expected, but for the case, as described, it works.)

+1
source

I have a similar solution for broofa's. However, this problem has the same problem. Here's the fiddle:

http://jsfiddle.net/2w3kt/


 $.fn.getStyleParent = function(property) { var $source = this.get(0), // only do for 1st element :P srcVal = $source.css(property), $element = null; $(this).parents().each(function() { var $this = $(this); if( $this.css(property) == srcVal ) element = $this; else return false; // stops the loop }); return $element; } 
+1
source

All Articles