Check if Element's Style contains CSS property using JS

avatar

Borislav Hadzhiev

Wed Jan 05 20222 min read

banner

Photo by Bobby Hendry

Check if Element's Style contains CSS property using JS #

To check if an element's style contains a specific CSS property, use the style object on the element to access the property and check if it's value is set, e.g. if (element.style.backgroundColor) {}. If the element's style does not contain the property, an empty string is returned.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style="background-color: salmon; width: 150px; height: 150px"> Hello world </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); // โœ… Check if CSS property is contained in Style if (box.style.backgroundColor) { console.log('value is', box.style.backgroundColor); } else { console.log('CSS property is not contained in style'); } // โœ… Remove property from style box.style.removeProperty('background-color'); // โœ… Add property to style box.style.setProperty('background-color', 'lime');

To check if an element's style contains a css property, we directly access the property on the style object.

If the value of the property is not set, an empty string is returned.

Notice that CSS property names that consist of multiple words are camel-cased, e.g. backgroundColor.

Our if block will run only if the background color property is set as an inline style on the element.

Otherwise, the else block is ran.

If you need to remove a CSS property from the element's inline styles, call the removeProperty method on the style object.

index.js
const box = document.getElementById('box'); // โœ… Remove property from style box.style.removeProperty('background-color');

The method removes the given property from the CSS style declaration object of the element.

Note that multi-word property names are hyphenated and not camel-cased.

Similarly, you can set or update a CSS property on the element's inline styles by using the setProperty() method.

index.js
const box = document.getElementById('box'); // โœ… Add property to style box.style.setProperty('background-color', 'lime');

The setProperty method sets a new value for the property on the element's CSS style declaration object.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee