Home > Web Front-end > CSS Tutorial > How Can I Retrieve All CSS Rules Applied to a Specific Element Using Pure JavaScript?

How Can I Retrieve All CSS Rules Applied to a Specific Element Using Pure JavaScript?

Susan Sarandon
Release: 2024-12-19 07:06:14
Original
188 people have browsed it

How Can I Retrieve All CSS Rules Applied to a Specific Element Using Pure JavaScript?

Get All CSS Rules Associated with an Element

Browser rendering involves compiling CSS rules and applying them to specific elements. This hierarchical process culminates in the final appearance of elements, as shown in browser tools like Firebug. However, accessing these computed CSS rules without additional plugins requires a custom solution in pure JavaScript.

Solution:

To retrieve CSS rules for an element, we can leverage JavaScript's DOM API and CSSRule objects. The following code snippet provides a cross-browser compatible 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;
}
Copy after login

This function takes an element as input and returns an array containing the CSS rules that apply to it. To retrieve the rules for a specific element, simply call css(document.getElementById('elementId')).

Example:

Consider the following HTML and CSS:

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

<p>
Copy after login

Calling css(document.getElementById('description')) would return the following array:

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

This array lists the two CSS rules that apply to the element, providing a clear understanding of its final appearance.

The above is the detailed content of How Can I Retrieve All CSS Rules Applied to a Specific Element 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