使用 JavaScript 按多个 ID 选择元素
使用 querySelectorAll()
方法通过多个 id 选择元素,例如 document.querySelectorAll('#box1, #box2, #box3')
。 该方法将包含一个或多个选择器的字符串作为参数,并返回匹配元素的集合。
以下是本文示例的 HTML。
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box1">Box 1</div> <div id="box2">Box 2</div> <div id="box3">Box 3</div> <script src="index.js"></script> </body> </html>
这是相关的 JavaScript 代码。
const boxes = document.querySelectorAll('#box1, #box2, #box3');
// 👇️ [div#box1, div#box2, div#box3]
console.log(boxes);
我们将多个以逗号分隔的选择器传递给 document.querySelectorAll()
方法,以获取 ID 为 box1、box2 和 box3 的元素的 NodeList。
如果没有一个选择器与元素匹配,则返回一个空的 NodeList。
传递给该方法的字符串必须是有效的 CSS 选择器字符串。 如果不是,则抛出
SyntaxError
异常。
如果我们有一个 ID 数组并且需要获取具有这些 ID 的元素的集合,请改用这种方法。
const ids = ['box1', 'box2', 'box3'];
const boxes = document.querySelectorAll(
ids.map(id => `#${id}`).join(', ')
);
// 👇️ [div#box1, div#box2, div#box3]
console.log(boxes);
我们传递给 Array.map
方法的函数将使用数组中的每个 ID 进行调用。
无论我们从回调函数返回什么,都会包含在
themap()
方法返回的新数组中。
最后一步是将 ID 数组连接成一个带有逗号分隔符的字符串。
如果需要遍历 NodeList,请使用 NodeList.forEach
方法。
const boxes = document.querySelectorAll('#box1, #box2, #box3');
// 👇️ [div#box1, div#box2, div#box3]
console.log(boxes);
boxes.forEach(box => {
console.log(box);
});
为 NodeList 中的每个元素调用我们传递给 forEach 方法的函数。
请注意,我们不能在 NodeList 上使用所有本机数组方法。
如果我们需要对集合执行更复杂的操作,请使用 Array.from
方法将其转换为数组。
const boxes = Array.from(
document.querySelectorAll('#box1, #box2, #box3')
);
// 👇️ [div#box1, div#box2, div#box3]
console.log(boxes);
// 👇️ true
console.log(Array.isArray(boxes));
Array.from()
方法采用类似数组的对象并将其转换为数组。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。