js remove specific css property

How to remove a specific CSS property using JavaScript

Have you ever wanted to remove a particular CSS property using JavaScript? Maybe you have an element on your website that has a specific style attribute that you want to get rid of dynamically. If that's the case, then continue reading to find out how to remove specific CSS properties with JavaScript.

Method 1: Using the removeProperty() method

The easiest way to remove a specific CSS property is by using the removeProperty() method. This method is available on the CSSStyleDeclaration interface, which represents a set of CSS style rules.


const element = document.querySelector("#my-element");
element.style.removeProperty("background-color");

In this example, we're selecting an element with the ID "my-element" and removing its background-color property. You can replace "background-color" with any other CSS property you want to remove.

Method 2: Setting the property to an empty string

Another way to remove a specific CSS property is by setting it to an empty string. This will effectively remove the property from the element's inline style attribute.


const element = document.querySelector("#my-element");
element.style.backgroundColor = "";

In this example, we're setting the background-color property to an empty string, which removes it from the element's inline style attribute.

Method 3: Using the CSSStyleDeclaration.setProperty() method

If you want to remove a specific CSS property and replace it with a new value, you can use the setProperty() method on the CSSStyleDeclaration interface.


const element = document.querySelector("#my-element");
element.style.setProperty("background-color", "");

In this example, we're removing the background-color property and replacing it with an empty string.

Conclusion

These are the three methods you can use to remove a specific CSS property using JavaScript. The first method is the easiest and most straightforward, but the other two methods may come in handy if you want to replace the removed property with a new value. Experiment with each method to see which one works best for your specific use case!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe