"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Method of obtaining HTML elements using JavaScript

Method of obtaining HTML elements using JavaScript

Posted on 2025-04-30
Browse:183

How to Get Computed Style Values from HTML Elements Using JavaScript?

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

Solution:

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.

Standard Method (W3C):

function getStyle(el, styleProp) {
  var value, defaultView = (el.ownerDocument || document).defaultView;
  if (defaultView && defaultView.getComputedStyle) {
    styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
    return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
  }
}

Here, property names must be in hyphen-separated format (e.g., "font-size"). Values will be returned in pixels.

IE Method:

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
    ...
  }
}

IE expects property names to be in camelCase format and returns values in the specified units. Note that this method has certain limitations.

Example Usage:

var element = document.getElementById("box");
var width = getStyle(element, "width");
console.log("Width: "   width);
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3