Last updated: Mar 5, 2024
Reading time·2 min
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.
<!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>
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 an element // box.removeAttribute('class');
We used the
Element.removeAttribute()
method to remove the style
attribute from the element.
If the attribute doesn't exist on the element, the removeAttribute()
method
doesn't throw an error, it simply returns undefined
.
If you want to
remove a specific CSS property
from the element's style, 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 the element box.removeAttribute('class');
You can learn more about the related topics by checking out the following tutorials: