使用 JavaScript 检查 Body 是否有特定的类
Check if Body has a specific Class using JavaScript
使用该classList.contains()
方法检查 body 元素是否具有特定类,例如document.body.classList.contains('my-class')
. 该方法返回一个布尔值——true
如果元素的类列表包含该类,false
否则。
以下是本文示例的 HTML。
索引.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <style> .bg-salmon { background-color: salmon; } </style> <body class="bg-salmon"> <div>Box 1</div> <script src="index.js"></script> </body> </html>
这是相关的 JavaScript 代码。
索引.js
const bodyHasClass = document.body.classList.contains( 'bg-salmon' ); if (bodyHasClass) { console.log('✅ body element has class'); } else { console.log('⛔️ body element does not have class'); }
对象的body
属性document
使我们能够访问body
元素。
我们使用
classList.contains
方法来检查body
元素是否具有特定类。
The method returns
true
if the provided class is contained in the element’s class list and false
otherwise.If you need to add or remove a class from the body
element, you can use the
classList.add()
and classList.remove()
methods.
index.js
// ✅ Add classes to <body> element document.body.classList.add('first-class', 'second-class'); // ✅ Remove classes from <body> element document.body.classList.remove('bg-salmon', 'third-class');
The classList.add
method adds one or more classes to the element.
If any of the provided classes already exists on the element, the classes will not get added a second time.
The classList.remove
method removes one or more classes from the element.
If any of the classes are not present on the element, the
remove()
method does not throw an error, it simply ignores the class.