Retrieving Applicable CSS Rules for Elements
Introduction:
Web browsers apply CSS styles from various stylesheets to elements to render them. Tools like Firebug expose this information, displaying the CSS inheritance tree for each element. This article sheds light on how to replicate this feature in pure JavaScript without browser plugins.
Solution:
To determine the CSS rules applied to an element:
Here's sample JavaScript code to implement this solution:
function css(el) { var sheets = document.styleSheets; var 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; }
To use this function, call css(document.getElementById('elementId')). It will return an array containing the applied CSS rules as strings.
Example:
Consider this sample HTML and CSS:
<style type="text/css"> p { color: red; } #description { font-size: 20px; } </style> <p>
Invoking css(document.getElementById('description')) will result in an array with two elements:
["p { color: red; }", "#description { font-size: 20px; }"]
This function provides a straightforward and cross-browser compatible approach to retrieve the applicable CSS rules for any given element in pure JavaScript.
The above is the detailed content of How to Programmatically Retrieve Applicable CSS Rules for Elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!