Home >Web Front-end >CSS Tutorial >How Can I Efficiently Retrieve an Element's Initially Defined CSS Property Values?

How Can I Efficiently Retrieve an Element's Initially Defined CSS Property Values?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 18:03:11468browse

How Can I Efficiently Retrieve an Element's Initially Defined CSS Property Values?

Extracting Element's CSS Property Values as Set

When needing to obtain the CSS property values of an element as they were initially defined, the function getMatchedStyle offers a solution. This function iterates through the matched CSS rules in descending order of priority, considering both element styles and property importance.

function getMatchedStyle(elem, property){
    var val = elem.style.getPropertyValue(property);
    if(elem.style.getPropertyPriority(property))
        return val;
    var rules = getMatchedCSSRules(elem);
    for(var i = rules.length; i--;){
        var important = r.style.getPropertyPriority(property);
        if(val == null || important){
            val = r.style.getPropertyValue(property);
            if(important)
                break;
        }
    }
    return val;
}

By considering property importance and element styles, getMatchedStyle accurately returns the CSS property value as set in the stylesheet.

Usage Example

Consider the following HTML and CSS code:

<div class="b">div 1</div>
<div>
div      { width: 100px; }
.d3      { width: auto !important; }
div#b    { width: 80%; }
div#c.c  { width: 444px; }
x, div.a { width: 50%; }
.a       { width: 75%; }

Executing the following JavaScript code:

var d = document.querySelectorAll('div');

for(var i = 0; i < d.length; ++i){
    console.log("div " + (i+1) + ":  " + getMatchedStyle(d[i], 'width'));
}

will output:

div 1:  100px
div 2:  50%
div 3:  auto
div 4:  44em

This demonstrates the function's ability to accurately extract the set CSS width values of the elements.

The above is the detailed content of How Can I Efficiently Retrieve an Element's Initially Defined CSS Property Values?. 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