Accessing Styles from HTML Elements with JavaScript Question: How can I retrieve the computed style values of an HTML element using JavaScript, specifically when the styles are defined in the tag?</p> <p><strong>Solution:</strong></p> <p>To obtain the computed style values, it is necessary to access the element's computed style. There are two approaches, with the standard DOM Level 2 method supported by most browsers, and the IE-specific element.currentStyle property.</p> <p><strong>Standard Method (W3C):</strong></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre>function getStyle(el, styleProp) { var value, defaultView = (el.ownerDocument || document).defaultView; if (defaultView && defaultView.getComputedStyle) { styleProp = styleProp.replace(/([A-Z])/g, "-").toLowerCase(); return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp); } }</pre><div class="contentsignin">Copy after login</div></div> <p>Here, property names must be in hyphen-separated format (e.g., "font-size"). Values will be returned in pixels.</p> <p><strong>IE Method:</strong></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre>if (el.currentStyle) { styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) { return letter.toUpperCase(); }); value = el.currentStyle[styleProp]; if (/^\d+(em|pt|%|ex)?$/i.test(value)) { // Convert non-pixel units to pixels ... } }</pre><div class="contentsignin">Copy after login</div></div> <p>IE expects property names to be in camelCase format and returns values in the specified units. Note that this method has certain limitations.</p> <p><strong>Example Usage:</strong></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre>var element = document.getElementById("box"); var width = getStyle(element, "width"); console.log("Width: " + width);</pre><div class="contentsignin">Copy after login</div></div>