Last updated: Jan 11, 2023
Reading time·2 min
Use the style.removeProperty()
method to remove CSS style properties from an
element.
The removeProperty()
method removes the provided CSS style property from the
element.
Here is the HTML for the examples.
<!doctype html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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.
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.
If you need to add a CSS style property to the element, use the
style.setProperty
method.
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.
null
You can also 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 null
, the property is removed from
the element.
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.
backgroundColor
instead of background-color
.The style
object allows us to read, set, and 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
.
const box = document.getElementById('box'); // ✅ Set CSS Properties box.style.backgroundColor = 'coral';
You can learn more about the related topics by checking out the following tutorials: