I want to use JavaScript to get the computed style of an element whose style has been changed by the stylesheet. The style of an element does not change using inline CSS, which means that the style property does not help at all. The only function I found in HTML that could help is getComputedStyle.
The problem with using getComputedStyle is that it returns all the properties of the element, even if the stylesheet has not redefined it for that element.
For example, let's say I have a stylesheet:
body { font-size: 13px; } div { color: blue; } .example { font-weight: bold; }
... and the following HTML:
<body> <div> This is a <span class="example">test</span> </div> </body>
When I run the following JavaScript on a span element:
window.getComputedStyle(spanElement)
... I get all the CSS attributes for this element:
background-attachment: scroll; background-clip: border-box; background-color: rgb(255, 255, 255); background-image: none; background-origin: padding-box; [...] text-anchor: start; writing-mode: lr-tb; glyph-orientation-horizontal: 0deg; glyph-orientation-vertical: auto; -webkit-svg-shadow: none; vector-effect: none;
What I want is only the styles that the element has redefined (i.e. not inherited), in this example it will be:
font-weight: bold;
Is there an easy way to get this information? If not, what is the best way to get these results? Ideally, I want a solution / algorithm that will run quickly on hundreds of these elements.
Initially, I thought that I could iterate over the parent elements of a node and compare all the values ββto determine which ones were not inherited, but it seems very inefficient to compare a hundred attributes for each individual node. There are only a dozen different classes, but each can happen hundreds of times, so some kind of caching mechanism can significantly improve performance.
My first idea of ββcaching values ββwas to keep the class name and its value (for example, cachedValues['.example'] := 'font-weight: bold;' ). The problem with this method is that CSS selectors can be very complex. For example, some properties are inherited from their parents, which means that in my original example, CSS spans not inside divs will display differently. So I decided to include the parent in cached values ββ(for example, cachedValues['div span.example'] := 'font-weight: bold;' ). The problem here is that CSS selectors can get a lot more complicated with pseudo-classes like :first-child .
CSS example:
div:first-child { color: red; } div { color: blue; }
HTML example:
<body> <div>Red line</div> <div>Blue line</div> </body>
In this example, if I saved cachedValues['div'] := 'font-color: red;' , this would be wrong for the second line.
Do you have any suggestions on how to solve this problem?