Skip to content
Advertisement

Get the css definition of an element

Is there a fast way to retrieve the CSS width definition (or any other CSS attribute) of an element?

Notes

  1. I need to know the actual definition, like 80% or 42vw, and NOT the calculated pixel dimension.
  2. The width might be set on different CSS selectors, as illustrated in the code below

Here is a sample of the markup/CSS I have:

JavaScript
JavaScript

Problem: I want to find out via JS, that the <section> has a width of 75%.

Unfortunately, getMatchedCSSRules() is exactly what I need, but it’s deprecated and already removed from browsers.

Advertisement

Answer

I found a way to determine the exact CSS definition of any element by inspecting the document.styleSheets collection.

Getting accurate results was quite complex, as the result needs to respect (a) media queries that match the current viewport and (b) evaluate the CSS specificity of selectors.

Here is a complete function that’s optimized for high performance – finding a single property among 40+ CSS files with a total of 15k+ of individual rules took 40-50ms

Here is the gist (might be more current than the code below)

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement