Reputation: 10675
Suppose I have
HTML
<foo>
<bar>
<baz>Hello!</baz>
</bar>
</foo>
CSS
foo {
color: red;
}
bar {
color: red;
}
How can I take an element and determine whether its color
style attribute was the result of matching a direct CSS rule or by inheritance?
// foo -> true - the first CSS rule directly applied a color to this element.
// bar -> true - the second CSS rule directly applied a color to this element. It didn't change the color that would have been inherited, but that's ok.
// baz -> false - The color in this element is purely inherited.
function isColorSetDirectly(DOMElement) {
...?
}
Using JS, I:
Can determine the effective color of text (Hello!
) in a tag (baz
) using getComputedStyle
.
Can tell if a style was applied directly with HTML using the style attribute by checking element.style.color
.
Can't tell if the rule that determined the style was directly applied to the element or if the element inherited the rule.
If CSS rules could be exhaustively enumerated, I could use element.matches/matchesSelector
for every CSS rule that defines color
. But since CSS rules can be set anywhere (external stylesheet, inline style tag, element style attribute, etc.) it seems difficult to enumerate all CSS rules that could affect an element.
The code initially loaded with the page (HTML/CSS) can't be changed but may be freely manipulated with JS.
Bonus
Is there a way to find out which element baz
is inheriting its color from?
Upvotes: 1
Views: 539
Reputation: 7243
You can use window.document.styleSheets[i].rules
to get CSS rules. You can get the selectorText
, style
, or the full cssText
. For info on how to use this: https://stackoverflow.com/a/27527462/804495
All stylesheets, regardless of if it was included via <link>
or <style>
will be in window.document.styleSheets
. However, this will not get element style.
To resolve this, you can use getComputedStyle
on an element as you mentioned. If an element has a style declaration that is not in any of the styleSheets
, then you know it is an inline style=
CSS rule, either applied directly or through its ancestor chain.
Is there a way to find out which element baz is inheriting its color from?
It's possible. To find out which element it is inherited from, you will have to iterate through the parent elements; however based on the way CSS declarations work this should be exhaustive.
Upvotes: 3
Reputation: 191
Use browser developer tools. Most modern browser has developer tools to help you debug CSS, javascript, network problems. Press F12 to start in Chrome, firefox (firebug plugin) and IE.
http://developer.chrome.com/devtools
http://msdn.microsoft.com/en-us/library/dd565628(v=vs.85).aspx
Upvotes: 0