Home >Web Front-end >CSS Tutorial >How Can I Retrieve All Applicable CSS Rules for an Element Using Pure JavaScript?

How Can I Retrieve All Applicable CSS Rules for an Element Using Pure JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-28 22:56:10348browse

How Can I Retrieve All Applicable CSS Rules for an Element Using Pure JavaScript?

Finding CSS Rules Applicable to an Element with JavaScript

In web development, accessing CSS elements of specific classes or IDs is a common task, often aided by tools and APIs. However, browsers compile all applicable CSS rules from various sources to determine an element's appearance. How can we replicate this functionality in pure JavaScript, without relying on browser plugins?

Identifying Computed CSS Rules

Consider the following HTML and CSS example:

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

<p>

In this case, the element p#description inherits two CSS rules: a red color and a font size of 20px. The goal is to determine the origin of these rules.

JavaScript Implementation

To achieve this, we can employ the following JavaScript 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

var rules = css(document.getElementById('elementId'));

The rules variable will now contain an array of all CSS rules applicable to the selected element.

Note:

This function relies on the Element.matches() method, which requires a cross-browser compatibility polyfill for older browsers. However, it provides a quick and efficient method of identifying CSS rules without additional browser plugins.

The above is the detailed content of How Can I Retrieve All Applicable CSS Rules for an Element 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