Remove all Styles from an Element using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 5, 2024
2 min

banner

# Remove all Styles from an Element using JavaScript

Use the removeAttribute() method to remove all styles from an element, e.g. box.removeAttribute('style').

The removeAttribute method will remove the style attribute from the element.

Here is the HTML for the examples.

index.html
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> <style> .bg-salmon { background-color: salmon; } </style> </head> <body> <div id="box" style="width: 100px; height: 100px" class="bg-salmon" > Box 1 </div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); // ✅ Remove all Styles from Element box.removeAttribute('style'); // ✅ Remove specific style from Element box.style.width = null; // ✅ Remove all classes from an element // box.removeAttribute('class');

remove all styles from element

The code for this article is available on GitHub

We used the Element.removeAttribute() method to remove the style attribute from the element.

The only parameter the method takes is the name of the attribute we want to remove.

If the attribute doesn't exist on the element, the removeAttribute() method doesn't throw an error, it simply returns undefined.

# Removing a specific CSS property from the element's styles

If you want to remove a specific CSS property from the element's style, set the property to null.

index.js
const box = document.getElementById('box'); // ✅ Remove specific style from Element box.style.width = null; // ✅ Multi word properties are camel-cased box.style.backgroundColor = null;

remove specific css property from the elements styles

The code for this article is available on GitHub

Conversely, if you need to update or set the specific CSS property, set it to a value that is not null.

index.js
const box = document.getElementById('box'); // ✅ Remove specific style from Element box.style.width = '200px';

If you need to remove all classes from an element, use the removeAttribute() method.

index.js
const box = document.getElementById('box'); // ✅ Remove all classes from the element box.removeAttribute('class');

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.