Explain Codes LogoExplain Codes Logo

How do you read CSS rule values with JavaScript?

javascript
css-engineering
javascript-utilities
css-selectors
Alex KataevbyAlex Kataev·Nov 10, 2024
TLDR

Fishing out computed CSS styles with getComputedStyle():

let style = getComputedStyle(document.querySelector('.example')); console.log(style.color); // Yields computed color, pretty simple, eh?

Not enough? Need to explore the entire styling sea for a specific CSS rule? Strap in, we're going deeper.

CSS expedition with document.styleSheets

We're going to find every occurrence of a specific selector in all your style sheets with this nifty function:

function getCssRulesBySelector(selector) { let results = []; // Our treasure chest // Let's sail through all stylesheets for (const sheet of document.styleSheets) { const rules = sheet.rules || sheet.cssRules; // Depending on the browser, y'know? // Dive into each rule of each stylesheet for (const rule of rules) { if (rule.selectorText === selector) { // Gotcha, CSS rule! results.push(rule.style.cssText || rule.cssText); } } } // Return all the CSS goodies as a string return results.join(' '); }

This function collates all CSS rules tied to the given selector. It's like a stash of CSS treasure.

Maneuvering pseudo-classes and media queries

Captain! We got pseudo-classes and media queries on the radar! No probs - our function's got the agility to handle these:

function getCssRulesBySelector(selector, includeMediaQueries = false) { let results = []; // ... if (rule.selectorText === selector) { results.push(rule.style.cssText || rule.cssText); } else if (includeMediaQueries && rule.conditionText) { rule.cssRules && Array.from(rule.cssRules) // Hunting CSS rules in the deep media queries sea .forEach(innerRule => { if (innerRule.selectorText === selector) { results.push(innerRule.style.cssText || innerRule.cssText); } }); } // ... }

Computed vs declared styles: The tale of the CSS tape

Do you know the difference between computed and declared values? Here's the difference: getComputedStyle() gives us the final value, post-CSS rules and inheritance:

  • It might not match your CSS value if another rule overrides it.
  • It won't show values non-applicable to that element (say, width on an inline element).

On the other hand, document.styleSheets gifts us the declared value:

  • Exactly what you wrote in your CSS.
  • Before specific overrides or user-agent styles apply.

Custom properties: The CSS scroll

Want to read CSS Variables (custom properties)? getComputedStyle() gets you what you need:

let rootStyle = getComputedStyle(document.documentElement); console.log(rootStyle.getPropertyValue('--my-variable')); // 🎁 It reveals the value!

The labyrinth of specificity

CSS specificity can tangle the applied styles on an element. This maze becomes evident when you're trying to solve the mystery of unexpected styling:

  • Inline styles have the highest specificity. You can say, it's the VIP pass!
  • !important gets to the front of the line. Kinda rude, but it works.
  • JavaScript might modify styles at runtime - it's the wizard!

Testing is your map to navigate through your styles, always keep it handy.