Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element from which CSS rule is being inherited

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?

like image 911
Joseph Silber Avatar asked Nov 05 '22 15:11

Joseph Silber


2 Answers

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.)

like image 64
broofa Avatar answered Nov 13 '22 23:11

broofa


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;
}
like image 37
Andy Avatar answered Nov 13 '22 22:11

Andy