使用 JavaScript 从元素中删除所有类
Remove all Classes from an Element using JavaScript
要从元素中删除所有类,请将元素的className
属性设置为空字符串,例如box.className = ''
.
将元素的className
属性设置为空字符串会清空元素的类列表。
这是示例的 HTML。
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> <style> .bg-salmon { background-color: salmon; } .text-white { color: white; } </style> </head> <body> <div id="box" class="text-white bg-salmon">Box 1</div> <script src="index.js"></script> </body> </html>
这是相关的 JavaScript 代码。
const box = document.getElementById('box'); // ✅ Remove all classes from an element box.className = '';
className
属性可用于读取、设置或更新元素属性的值class
。
使用 removeAttribute 从元素中删除所有类
另一种方法是使用
Element.removeAttribute()
方法。
remove 方法将从class
元素中移除属性,有效地移除元素的所有类。
const box = document.getElementById('box'); // ✅ Remove all classes from element box.removeAttribute('class');
className
class
该方法只是从元素中removeAttribute
删除属性。class
如果元素没有class
设置属性,该removeAttribute
方法将不会抛出错误,它只会返回一个undefined
值。
使用 JavaScript 删除除一个类之外的所有类
To remove all classes from an element except one, use the className
property
on the element to set its class string to the class you want to keep.
The className
property can be used to read, set or update the class of the DOM
element.
Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> <style> .bg-yellow { background-color: yellow; } .text-red { color: red; } .big { padding: 20px; } </style> </head> <body> <div id="box" class="bg-yellow text-red big">Box 1</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const box = document.getElementById('box'); // 👇️ Remove all classes except bg-yellow box.className = 'bg-yellow';
We used the document.getElementById()
method to select the element by its
id
.
We then set the element’s
className
property to the only class we want to keep.
An alternative approach that achieves the same result is to use the
setAttribute()
method.
const box = document.getElementById('box'); box.setAttribute('class', 'bg-yellow');
The
setAttribute
method sets the value of an attribute on the specified element.
When we use the setAttribute
method on an element that already has a class
attribute, we are effectively replacing the value of the element’s class.
An alternative and more manual approach to remove all classes from an element
except one is to use the classList.remove()
method.
const box = document.getElementById('box'); box.classList.remove('text-red', 'big');
The
remove()
method takes one or more class names as parameters and removes the classes from
the element.
If the class does not exist on the element, the remove()
method does not throw
an error, it just ignores the class.
Which approach you pick is a matter of personal preference.
我会采用将className
元素的属性设置为我想要保留的类的方法,因为它是 3 中最直接和最容易阅读的方法。