Remove CSS Style Property from an Element using JavaScript

avatar

Borislav Hadzhiev

Sat Jan 01 20222 min read

banner

Photo by Claude Piché

Remove CSS Style Property from an Element #

Use the style.removeProperty() method to remove CSS style properties from an element, e.g. box.style.removeProperty('background-color'). The removeProperty() method removes the provided CSS style property from the element.

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: yellow; color: red; width: 100px; height: 100px" > Box 1 </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); // ✅ Remove CSS properties box.style.removeProperty('width'); box.style.removeProperty('height'); box.style.removeProperty('background-color'); // ✅ Set CSS Properties // box.style.setProperty('background-color', 'salmon');

We used the style.removeProperty method to remove CSS properties from the element.

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

If you need to add a CSS style property to the element, you can use the style.setProperty method.

index.js
const box = document.getElementById('box'); // ✅ Set CSS Properties box.style.setProperty('background-color', 'salmon');

The style.setProperty method sets or updates a CSS style property on the DOM element.

Alternatively, you can use a more direct approach.

You can remove CSS style properties from an element by setting the property to a null value, e.g. box.style.backgroundColor = null;. When an element's CSS property is set to a null value, the property is removed from the element.

index.js
const box = document.getElementById('box'); // ✅ Remove CSS properties box.style.backgroundColor = null; box.style.width = null; // ✅ Set CSS Properties // box.style.backgroundColor = 'coral';

We can access CSS properties on the element's style object.

Notice that instead of hyphenating property names, we use camel-cased names when using this approach, e.g. backgroundColor instead of background-color.

The style object allows us to read, set, or update the values of CSS properties on the element.

If you want to set a CSS property on the element, set the property to a value other than null.

index.js
const box = document.getElementById('box'); // ✅ Set CSS Properties box.style.backgroundColor = 'coral';
Use the search field on my Home Page to filter through my more than 1,000 articles.