迹忆客 专注技术分享

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

使用 JavaScript 按多个 ID 选择元素

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

使用 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() 方法采用类似数组的对象并将其转换为数组。

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便