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