使用 JavaScript 从 Body 元素中删除一个类

使用 JavaScript 从 Body 元素中删除一个类

Remove a class from the Body element using JavaScript

要从 body 元素中删除一个类,请调用classList.remove()body 对象上的方法,例如document.body.classList.remove('my-class')
remove()方法从元素的类列表中删除一个或多个类。

以下是本文示例的 HTML。

索引.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .salmon { background-color: salmon; } </style> </head> <body class="salmon"> <div>Box Content here</div> <script src="index.js"></script> </body> </html>

这是相关的 JavaScript 代码。

索引.js
// ✅ Remove class from Body document.body.classList.remove('salmon'); // ✅ Add class to Body // document.body.classList.add('my-class');

我们可以body直接在document对象上访问元素。

我们使用
classList.remove
方法从
元素中删除
salmon类。body

The classList.remove() method can be used to remove classes from any type of element, not just the body.

Note that you can pass as many classes as necessary to the remove() method.

index.js
document.body.classList.remove( 'salmon', 'second-class', 'third-class' );
If any of the classes is not present on the element, the remove() method ignores the class and does not throw an error.

Conversely, you can add a class to the body element, by calling the
classList.add() method on the element.

index.js
// ✅ Add class to Body document.body.classList.add( 'first-class', 'second-class', 'third-class' );

If any of the classes passed to the add() method is already present on the
body element, it will be omitted.

When using the classList.remove() and classList.add() methods, you don’t
have to worry about:

  • getting errors when removing a class that is not present on the element

  • adding the same class multiple times to the same element