How to Retrieve CSS Property Values for Elements in JavaScript?

Susan Sarandon
Release: 2024-10-23 21:33:30
Original
371 people have browsed it

How to Retrieve CSS Property Values for Elements in JavaScript?

Reading CSS Properties of Elements Using JavaScript

Problem:

How to obtain the value of a CSS property for an element using JavaScript, considering that the stylesheet is linked externally to the webpage?

Solution:

There are two primary approaches:

1. Using document.styleSheets:

This method involves manually iterating through the document.styleSheets array and parsing the CSS rules to find the desired property. However, this approach is not recommended as it's resource-intensive and not practical for most scenarios.

2. Creating a Matching Element and Using getComputedStyle:

This method creates an element with the same CSS selector as the target element and uses the getComputedStyle method to retrieve the property value. The advantage of this approach is that it accounts for all inherited styles and any styles applied dynamically.

Code Example:

To retrieve the "color" property of a div with the class "layout," use the following code:

<code class="javascript">function getStyleProp(elem, prop){
    if(window.getComputedStyle)
        return window.getComputedStyle(elem, null).getPropertyValue(prop);
    else if(elem.currentStyle)
        return elem.currentStyle[prop]; //IE
}</code>
Copy after login

Usage:

<code class="javascript">window.onload = function(){
    var d = document.createElement("div"); //Create div
    d.className = "layout";                //Set class = "layout"
    alert(getStyleProp(d, "color"));       //Get property value
}</code>
Copy after login

Additional Notes:

To ignore inline style definitions on the current element, use the getNonInlineStyle function:

<code class="javascript">function getNonInlineStyle(elem, prop){
    var style = elem.cssText; //Cache the inline style
    elem.cssText = "";        //Remove all inline styles
    var inheritedPropValue = getStyle(elem, prop); //Get inherited value
    elem.cssText = style;     //Add the inline style back
    return inheritedPropValue;
}</code>
Copy after login

The above is the detailed content of How to Retrieve CSS Property Values for Elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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