使用 JS 检查具有特定 ID 的元素是否具有子节点
使用 querySelector()
方法检查一个元素是否有一个具有特定 id 的子元素,例如 if (box.querySelector('#child-3') !== null) {}
。 querySelector
方法返回与提供的选择器匹配的第一个元素或没有元素匹配的 null。
以下是本文示例的 HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="box">
<p>Child 1</p>
<p>Child 2</p>
<p id="child-3">Child 3</p>
</div>
<script src="index.js"></script>
</body>
</html>
这是相关的 JavaScript 代码。
const box = document.getElementById('box');
if (box.querySelector('#child-3') !== null) {
console.log('✅ element has child with id of child-3');
} else {
console.log('⛔️ element does NOT have child with id');
}
我们使用 getElementById
方法来选择父元素。
querySelector
方法可以限定为特定元素,并返回第一个元素,该元素是调用该方法的元素的后代,并且与提供的选择器匹配。
如果没有元素与提供的选择器匹配,则
querySelector
方法返回 null。
在我们的 if 语句中,我们检查返回值是否不等于 null。 如果找到元素,则运行 if 块,否则运行 else 块。
如果我们还没有选择父元素,可以一步完成。
if (document.querySelector('#box #child-3') !== null) {
console.log('✅ element has child with id of child-3');
} else {
console.log('⛔️ element does NOT have child with id');
}
我们使用
querySelector
方法选择一个 id 为 child-3 的元素,该元素是 id 为 box 的元素的后代。
我们传递给 querySelector
方法的选择器可以根据需要指定。 以下示例仅检查元素的任何直接子元素是否具有 id。
if (document.querySelector('#box > #child-3') !== null) {
console.log('✅ element has child with id of child-3');
} else {
console.log('⛔️ element does NOT have child with id');
}
上面的选择器不会匹配 id
为 box
且 id
为 child-3
的元素的任何嵌套子元素。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。