Home >Web Front-end >CSS Tutorial >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>
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>
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>
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!