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
Release: 2024-12-16 18:03:11
Original
412 people have browsed it

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;
}
Copy after login

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>
Copy after login
div      { width: 100px; }
.d3      { width: auto !important; }
div#b    { width: 80%; }
div#c.c  { width: 444px; }
x, div.a { width: 50%; }
.a       { width: 75%; }
Copy after login

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'));
}
Copy after login

will output:

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

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!

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