Determining All CSS Rules Affecting an Element in Pure JavaScript
In web development, inspecting the raw stylesheets loaded by the browser provides only a partial understanding of the CSS rules applied to elements. This is because browsers compile all CSS rules and apply them to elements based on inheritance, resulting in a complex inheritance tree that's not immediately apparent in the stylesheet.
For developers seeking a pure JavaScript solution to reproduce this feature, retrieving detailed information about the computed CSS rules affecting an element poses a significant challenge without relying on additional browser plugins. However, here's a comprehensive 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 text for each matching rule.
To illustrate its usage, consider the following HTML and CSS:
HTML
<style type="text/css"> p { color :red; } #description { font-size: 20px; } </style> <p>
JavaScript
var rules = css(document.getElementById('description')); console.log(rules); // ['color: red;', 'font-size: 20px;']
In this example, the function identifies two matching CSS rules: one specifying a red color for all
elements and another setting the font size to 20 pixels for the element with the ID #description.
The returned array allows further exploration of each rule's details by referencing the CSSRule object documentation. This approach provides a comprehensive and browser-compatible method for extracting the computed CSS rules applied to an element without the need for additional plugins, enabling developers to deeply inspect and debug their styling.
The above is the detailed content of How can I retrieve all CSS rules affecting an element in pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!