Remove all Styles from an Element using JavaScript

avatar

Borislav Hadzhiev

Sun Jan 02 20221 min read

banner

Photo by Wira Dyatmika

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 in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <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>

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 element // box.removeAttribute('class');

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 does not exist on the element, the removeAttribute() method does not throw an error, it simply returns undefined.

If you want to remove a specific CSS property from the element's style, you can 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;

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 element box.removeAttribute('class');
Use the search field on my Home Page to filter through my more than 1,000 articles.