Home >Web Front-end >CSS Tutorial >How Can I Determine Which CSS Rules Affect a Specific Element Using Only JavaScript?

How Can I Determine Which CSS Rules Affect a Specific Element Using Only JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-16 22:57:19312browse

How Can I Determine Which CSS Rules Affect a Specific Element Using Only JavaScript?

Determining CSS Rules Affecting Elements in JavaScript

Problem:

Many web development tools offer functionality for selecting elements based on class or ID. However, it is possible to delve deeper into the rendering process of browsers by inspecting the raw CSS stylesheets they load. CSS rules are compiled and applied to elements from multiple stylesheets, creating an intricate inheritance tree.

Question:

How can we replicate this feature in pure JavaScript without relying on additional browser plugins?

Example:

For a given element such as:

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

<p>

The p#description element is affected by two CSS rules: a red color and a font size of 20px.

Answer:

Function:

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

Usage:

calling css(document.getElementById('elementId')) 

This function returns an array containing each CSS rule that matches the passed element.

The above is the detailed content of How Can I Determine Which CSS Rules Affect a Specific Element Using Only 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