迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 >

使用 JS 检查具有特定 ID 的元素是否具有子节点

作者:迹忆客 最近更新:2022/12/19 浏览次数:

使用 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');
}

上面的选择器不会匹配 idboxidchild-3 的元素的任何嵌套子元素。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便