迹忆客 专注技术分享

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

使用 JavaScript 按 ID 获取子元素

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

通过 id 获取子元素:

  1. 使用 document.querySelector() 方法获取父元素。
  2. 在父元素上调用 querySelector 方法,将 id 作为参数传递给它。
  3. 例如, parent.querySelector('#first') 首先获取具有 id 的孩子。

这是文章中示例的 HTML。

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="parent">
      <div id="first">Child 1</div>
      <div>Child 2</div>
    </div>

    <script src="index.js"></script>
  </body>
</html>

这是相关的 JavaScript 代码。

index.js

const parent = document.querySelector('#parent');
console.log(parent); // 👉️ div#parent

const child = parent.querySelector('#first');
console.log(child); // div#first

我们使用 document.querySelector 方法通过其 id 获取父元素。

在这种情况下,我们可以使用 ocument.getElementById 方法来获得相同的结果,例如:

const parent = document.getElementById('parent');

请注意,当使用 querySelector 方法时,我们在 id 前面加上一个哈希 #,而在使用 getElementById 时 - 我们没有。

下一步是在父元素上调用 querySelector 方法。

querySelector 方法作用于特定元素时,它只选择调用该方法的元素的子元素。

Element.querySelector 方法返回与提供的选择器匹配的第一个元素。

在示例中,我们选择了一个 id 值设置为 first 的子元素。

const parent = document.querySelector('#parent');
console.log(parent); // 👉️ div#parent

const child = parent.querySelector('#first');
console.log(child); // div#first

当将 id 传递给 querySelector 方法时,我们选择了元素的任何子元素。

这包括具有提供的 id 的嵌套子级。

但是,这并不重要,因为我们页面上的 ID 应该是唯一的。

在一个页面上有多个具有相同 id 的元素可能会导致令人困惑的行为和难以跟踪的错误。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便