How to get an HTML element's style values in JavaScript?
To fetch an element's computed style in JavaScript, use **getComputedStyle()**
. To fetch a specific style, like the color
, of an element #elementID
, use:
This command gives you the actual color value the browser applied to the element.
To cater for cross-browser compatibility, remember that **getComputedStyle()**
is applicable in most browsers, but for Internet Explorer, use **element.currentStyle**
as an alternate. Here is a helper function:
Navigating browser inconsistencies
There are several inconsistencies across browsers, specifically with IE and property name differences. For example, JavaScript represents the CSS float
property as cssFloat
, whereas it's styleFloat
in IE's DOM. You'll need to adjust these names to maintain compatibility.
In the sphere of units, IE communicates sizes in the original units of measurement (em
or %
), while other browsers transport them to pixels.
When dealing with colors, keep an eye for notation differences. Conventional browsers may use RGB or hexadecimal color values, while IE could use color names.
Reducing reliance on libraries
It's tempting to lean on libraries such as jQuery. However, with native JS methods improving constantly, it's often more practical and efficient to get styles with pure JavaScript. This strategy keeps your code lighter and your web page faster.
Consistency and efficiency in your wardrobe
Dealing with a full closet
When you're managing multiple properties, instead of repeatedly calling **getPropertyValue**
, you can use a reduce method to group values:
You end up with an object holding the computed style values for the specified properties. It is both cleaner and lightens the load on the browser’s rendering engine.
Attaining uniformity
Be mindful, manage your units consistently across all browsers. If you need pixel values, you may need to convert in IE manually.
Similarly, when dealing with colors, ensure you convert the formats to a standard such as hex or rgb, where necessary.
Was this article helpful?