Explain Codes LogoExplain Codes Logo

How to get an HTML element's style values in JavaScript?

javascript
browser-inconsistencies
native-js-methods
css-properties
Anton ShumikhinbyAnton Shumikhin·Dec 22, 2024
TLDR

To fetch an element's computed style in JavaScript, use **getComputedStyle()**. To fetch a specific style, like the color, of an element #elementID, use:

var color = getComputedStyle(document.getElementById('elementID')).color;

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:

function getStyle(element, property) { if (window.getComputedStyle) { return window.getComputedStyle(element).getPropertyValue(property); } else { // Guess who's back, back again, IE's back, tell a friend. return element.currentStyle[property]; } }

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:

const styles = window.getComputedStyle(element); const neededProps = ['marginTop', 'backgroundColor', 'flexGrow']; const styleObject = neededProps.reduce((obj, prop) => { obj[prop] = styles.getPropertyValue(prop); // IT'S MINE NOW. return obj; }, {});

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.