使用 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 的元素的任何嵌套子元素。