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
Mary-Kate OlsenOriginal
2024-12-19 00:28:11400browse

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>

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;
}

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; }"]

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!

Statement:
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