To actually determine if the css style has been inherited or installed on the element itself, you will need to implement the exact rules that browsers apply to determine the value used for a particular style for the element.
You will need to implement this specification , which defines how calculated and used values are calculated.
CSS selectors may not always follow parent-child relationships, which may have simplified issues. Consider this CSS.
body { color: red; } div + div { color: red; }
and the following HTML:
<body> <div>first</div> <div>second</div> </body>
Both first and second wil are displayed in red, however, the first div is red because it inherits from the parent. The second div is red because the CSS div + div rule is applied to it, more specifically. Looking at the parent, we will see that it has the same color, but this is not where the second div gets it.
Browsers do not expose any internal calculations except the getComputedStyle interface.
A simple but erroneous solution would be to execute each selector from the style sheets and check if the given element satisfies the selector. If so, suppose the style was applied directly to the element. Say you wanted to go through each style in the first stylesheet,
var myElement = $('..'); var rules = document.styleSheets[0].cssRules; for(var i = 0; i < rules.length; i++) { if (myElement.is(rules[i].selectorText)) { console.log('style was directly applied to the element'); } }
Anurag Feb 15 '11 at 6:24 2011-02-15 06:24
source share