Retrieving Style Values from HTML Elements in JavaScript without Libraries When accessing the style of HTML elements through JavaScript, you may face challenges in retrieving values set by the tag. Unlike inline styles set through the element's attributes, styles defined in the <style> tag require a different approach.</p> <p>To obtain computed style values, including those defined in the <style> tag, you can utilize the following cross-browser function:</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre>function getStyle(el, styleProp) { var value, defaultView = (el.ownerDocument || document).defaultView; // W3C standard way: if (defaultView && defaultView.getComputedStyle) { // sanitize property name to css notation // (hypen separated words eg. font-Size) styleProp = styleProp.replace(/([A-Z])/g, "-").toLowerCase(); return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp); } else if (el.currentStyle) { // IE // sanitize property name to camelCase styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) { return letter.toUpperCase(); }); value = el.currentStyle[styleProp]; // convert other units to pixels 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; } }</pre><div class="contentsignin">Copy after login</div></div> <p><strong>Usage:</strong></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre>// Getting width style value var width = getStyle(document.getElementById("box"), "width"); // Getting color style value (may differ between browsers) var color = getStyle(document.getElementById("box"), "color");</pre><div class="contentsignin">Copy after login</div></div>