Borislav Hadzhiev
Sun Jan 02 2022·1 min read
Photo by Wira Dyatmika
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.
<!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.
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.
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
.
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
.
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.
const box = document.getElementById('box'); // ✅ Remove all classes from element box.removeAttribute('class');