用 JavaScript 的 querySelectorAll() 选择并遍历所有匹配元素

querySelectorAll() 返回静态 NodeList,包含按文档顺序排列的所有层叠样式表(CSS)选择器匹配项。没有匹配时列表为空。若要包含后来加入的元素,需要重新查询。

读取所有匹配元素

用 length 读取数量,用 [0] 读取首个元素。??? 之类的无效选择器会抛出 SyntaxError。有效但无匹配的选择器返回长度为 0 的列表。请参阅 querySelectorAll()。

{
  const items = document.querySelectorAll('#list .item');
  console.log(items.length);
  if (items.length > 1) {
    console.log(items[1].textContent);
  }

  const missing = document.querySelectorAll('.missing');
  console.log(missing.length); // 0
}

遍历 NodeList 并转换成数组

用 forEach() 逐个处理元素。需要 map() 等数组方法时,可用 Array.from(items) 转换,也可直接传入映射函数。只需首个匹配时,请参阅 querySelector()。

{
  const items = document.querySelectorAll('#list .item');
  items.forEach(item => item.classList.add('selected'));

  const labels = Array.from(items, item => item.textContent);
  console.log(labels);
}

选择直接子元素或组合选择器

从元素上查询 .item 可以匹配嵌套的后代。使用 :scope > .item 可限定为起始元素的直接子元素。逗号用于组合备选条件,每个匹配元素只会出现一次。请参阅 :scope。

{
  const list = document.createElement('div');
  list.innerHTML = '<p id="direct" class="item"></p><div><p id="nested" class="item warning"></p></div>';

  const descendants = list.querySelectorAll('.warning, .item');
  const children = list.querySelectorAll(':scope > .item');
  console.log(Array.from(descendants, item => item.id)); // ['direct', 'nested']
  console.log(Array.from(children, item => item.id));    // ['direct']
}

在控制台运行代码。即使 .warning 写在前面,第一个结果仍按文档顺序返回 ['direct', 'nested']。第二个结果只有 ['direct']。

文档变化后重新查询

添加或删除元素后,之前取得的列表保留原成员。它仍然引用原始节点,因此可以读到修改后的文本。运行下面的片段前先打开完整示例。重新查询可包含新增元素。

{
  const list = document.querySelector('#list');
  const before = document.querySelectorAll('#list .item');
  const item = document.createElement('li');
  item.className = 'item';
  list.append(item);

  console.log(before.length);
  console.log(document.querySelectorAll('#list .item').length);
}

运行会改变列表的完整示例

将 HTML 以 UTF-8 保存为 query-selector-all-example.html 并打开。添加一项后,初始数量仍是 2,新查询变为 3。突出显示当前三项,重置后计数恢复到 2、2 和 0。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>比较 querySelectorAll 的结果</title>
  <style>.selected { background: #fff2a8; }</style>
</head>
<body>
<h1>查找所有匹配元素</h1>
<ul id="list">
  <li class="item">第一项</li>
  <li class="item">第二项</li>
</ul>
<button id="add" type="button">添加项目</button>
<button id="mark" type="button">突出显示当前项目</button>
<button id="reset" type="button">重置</button>
<pre id="output" aria-live="polite"></pre>
<script>
const list = document.querySelector('#list');
const initial = document.querySelectorAll('#list .item');
const output = document.querySelector('#output');

function show() {
  const current = document.querySelectorAll('#list .item');
  const selected = document.querySelectorAll('#list .selected');
  output.textContent = `初始查询: ${initial.length}\n新查询: ${current.length}\n已突出显示的项目: ${selected.length}`;
}

document.querySelector('#add').addEventListener('click', () => {
  const item = document.createElement('li');
  item.className = 'item added';
  item.textContent = `新增项目 ${list.children.length + 1}`;
  list.append(item);
  show();
});
document.querySelector('#mark').addEventListener('click', () => {
  document.querySelectorAll('#list .item').forEach(item => {
    item.classList.add('selected');
  });
  show();
});
document.querySelector('#reset').addEventListener('click', () => {
  list.querySelectorAll('.added').forEach(item => item.remove());
  list.querySelectorAll('.selected').forEach(item => item.classList.remove('selected'));
  show();
});
show();
</script>
</body>
</html>