Home >Web Front-end >CSS Tutorial >How to Retrieve Style Values from HTML Elements using Pure JavaScript?
Retrieving Style Values from an HTML Element using JavaScript
Obtaining the style attributes of an HTML element is essential for manipulating its appearance dynamically. This article delves into the nuances of retrieving style values using pure JavaScript, without the aid of any external libraries.
CurrentStyle vs. Computed Properties
To access style values, we need to differentiate between inline styles (defined within the element's style attribute) and computed properties (the actual applied styles).
Internet Explorer uses the element.currentStyle property to retrieve inline styles, which hold values in their original units.
Mozilla and other modern browsers rely on the document.defaultView.getComputedStyle method to provide computed properties. These values are normalized to pixels, providing a consistent representation across browsers.
Cross-Browser Solution
The following function offers a cross-browser solution for retrieving both inline and computed styles:
function getStyle(el, styleProp) { var value, defaultView = (el.ownerDocument || document).defaultView; // Convert styleProp to compatible notation styleProp = styleProp.replace(/([A-Z])/g, "-").toLowerCase(); // Modern browsers: computed properties if (defaultView && defaultView.getComputedStyle) { return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp); } else if (el.currentStyle) { // IE: inline properties // Convert styleProp to camelCase notation styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) { return letter.toUpperCase(); }); value = el.currentStyle[styleProp]; // Normalize units on IE if (/^\d+(em|pt|%|ex)?$/i.test(value)) { return (function(value) { var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left; el.runtimeStyle.left = el.currentStyle.left; el.style.left = value || 0; value = el.style.pixelLeft + "px"; el.style.left = oldLeft; el.runtimeStyle.left = oldRsLeft; return value; })(value); } return value; } }
Example
To retrieve the inline width property of an element with the id "box" (set via a style tag):
alert (getStyle(document.getElementById("box"), "width"));
To retrieve the computed width property, which takes into account any cascading or inherited styles:
alert (getStyle(document.getElementById("box"), "width"));
Limitations
This function does not handle color values perfectly. The modern browsers will return colors in the rgb notation, while IE will maintain their original definition.
The above is the detailed content of How to Retrieve Style Values from HTML Elements using Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!