使用 JavaScript 检查父元素是否有特定的类
JavaScript 中要检查父元素是否具有特定类:
-
使用
closest()
方法,将其作为参数传递给类选择器。 - 如果存在具有特定类的父级,则该方法返回该元素。
- 如果不存在具有所提供类的父级,则该方法返回 null。
以下是本文示例的 HTML。
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="parent-1"> <div class="parent2"> <div id="child">Box 1</div> </div> </div> <script src="index.js"></script> </body> </html>
下面是JavaScript代码
// ✅ Check if any of the parent elements have class `parent-1`
const child = document.getElementById('child');
const parentHasClass = child.closest('.parent-1') !== null;
console.log(parentHasClass); // 👉️ true
// ✅ Check if DIRECT parent element has class `parent-1`.
const directParentHasClass =
child.parentElement?.classList.contains('parent-1');
console.log(directParentHasClass); // 👉️ false
我们使用 Element.closest()
方法来选择具有 parent-1 类的父元素。
closest()
方法遍历元素及其父元素,直到找到与提供的选择器匹配的节点。
如果元素本身与选择器匹配,则返回该元素。如果不存在与提供的选择器匹配的元素,则 closest()
方法返回 null。
parentHasClass
变量存储一个布尔值:
- 如果 id 为 child 的 div 的父元素包含 parent-1 类,则为真。
- 如果没有则为假。
这种方法不会专门检查直接父元素是否包含该类,它会检查层次结构中任何位置的父元素是否包含提供的类。
要检查元素的直接父级是否具有特定类:
-
使用
parentElement
属性选择元素的父级。 -
使用
classList.contains()
方法检查父类是否包含该类。 - 如果元素的类列表包含该类,则该方法返回 true,否则返回 false。
const child = document.getElementById('child');
// ✅ Check if DIRECT parent element has class `parent-1`.
const directParentHasClass =
child.parentElement?.classList.contains('parent-1');
console.log(directParentHasClass); // 👉️ false
parentElement
属性返回 DOM 节点的父元素,如果节点没有父元素或其父元素不是 DOM 元素,则返回 null。
如果元素没有父元素,我们使用可选的链接 (?.) 运算符来短路而不是抛出错误。
classList.contains
方法返回一个布尔值——如果该类包含在元素的类列表中则为 true,否则为 false。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。