Home >Web Front-end >CSS Tutorial >How Can I Retrieve All CSS Rules Applied to a Specific Element Using Pure JavaScript?
Get All CSS Rules Associated with an Element
Browser rendering involves compiling CSS rules and applying them to specific elements. This hierarchical process culminates in the final appearance of elements, as shown in browser tools like Firebug. However, accessing these computed CSS rules without additional plugins requires a custom solution in pure JavaScript.
Solution:
To retrieve CSS rules for an element, we can leverage JavaScript's DOM API and CSSRule objects. The following code snippet provides a cross-browser compatible solution:
function css(el) { var sheets = document.styleSheets, ret = []; el.matches = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector || el.oMatchesSelector; for (var i in sheets) { var rules = sheets[i].rules || sheets[i].cssRules; for (var r in rules) { if (el.matches(rules[r].selectorText)) { ret.push(rules[r].cssText); } } } return ret; }
This function takes an element as input and returns an array containing the CSS rules that apply to it. To retrieve the rules for a specific element, simply call css(document.getElementById('elementId')).
Example:
Consider the following HTML and CSS:
<style type="text/css"> p { color :red; } #description { font-size: 20px; } </style> <p>
Calling css(document.getElementById('description')) would return the following array:
[ "p { color: red; }", "#description { font-size: 20px; }" ]
This array lists the two CSS rules that apply to the element, providing a clear understanding of its final appearance.
The above is the detailed content of How Can I Retrieve All CSS Rules Applied to a Specific Element Using Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!