Home > Web Front-end > CSS Tutorial > How Can I Inspect a CSS Inheritance Tree Using Pure JavaScript?

How Can I Inspect a CSS Inheritance Tree Using Pure JavaScript?

Mary-Kate Olsen
Release: 2024-12-19 00:28:11
Original
461 people have browsed it

How Can I Inspect a CSS Inheritance Tree Using Pure JavaScript?

Inspecting CSS Inheritance Tree using JavaScript

Consider a web page with a p element with the id "description":

<style type="text/css">
    p { color :red; }
    #description { font-size: 20px; }
</style>

<p>
Copy after login

When the browser renders this element, it merges all applicable CSS rules into a single inheritance tree. How can we replicate this in pure JavaScript, without relying on browser plugins?

Solution:

In order to inspect the CSS rules applied to an element, we can traverse the document's stylesheets and match the element's selectors. Here's a cross-browser JavaScript function to achieve this:

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;
}
Copy after login

Calling css(document.getElementById('description')) returns an array of CSS rule strings applied to the element, in this case:

["p { color :red; }", "#description { font-size: 20px; }"]
Copy after login

This function allows developers to access the source of computed CSS rules, aiding in debugging and understanding web page styling.

The above is the detailed content of How Can I Inspect a CSS Inheritance Tree Using Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template