使用 JavaScript 按 ID 获取子元素
通过 id 获取子元素:
-
使用
document.querySelector()
方法获取父元素。 -
在父元素上调用
querySelector
方法,将 id 作为参数传递给它。 -
例如,
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 的元素可能会导致令人困惑的行为和难以跟踪的错误。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。