How to read CSS rule values with JavaScript?

Spread the love

Sometimes, we want to read CSS rule values with JavaScript.

In this article, we’ll look at how to read CSS rule values with JavaScript.

How to read CSS rule values with JavaScript?

To read CSS rule values with JavaScript, we use the document.styleSheets property.

For instance, we write

for (const sheet of document.styleSheets) {
  for (const cssRule of sheet.cssRules) {
    console.log(cssRule.selectorText);
  }
}

to loop through the style elements looping through document.styleSheets with a for-of loop.

Then we loop through the rules in each sheet by looping through sheet.cssRules.

In it, we get the selector of each rule with cssRule.selectorText.

Conclusion

To read CSS rule values with JavaScript, we use the document.styleSheets property.

Leave a Reply

Your email address will not be published. Required fields are marked *