In jQuery, we can easily get the CSS value for a given element with the css
method:
$('#myElement').css('line-height'); // e.g. '16px'
Now, since this CSS value might have been inherited from a parent element, is there any way to know which element has this rule applied to it?
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 I can just fire up Web Inspector
/Dev Tools
/Firebug
, but I want to get it programmatically.
Is this at all possible?
Walk up the parentElement chain checking the css() value of each element. The first element with a parent().css() value that's different is (probably) the element being targeted by the CSS rule selector.
See this fiddle for an example: http://jsfiddle.net/broofa/VPWV9/2/ (See the console.log output)
(Note: there are almost surely complex cases where this won't work as expected but for the case as described, it works.)
I have a similar solution to broofa's. It also has the same problem though. 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With