用 JavaScript 的 getElementsByTagName() 按标签选择元素

document.getElementsByTagName('p') 返回按文档顺序排列的 HTMLCollection。在元素上调用该方法可查找其后代。更改文档时,集合会随之更新。

在整个文档中选择标签

可以通过索引和 length 读取集合。没有匹配时,collection[0] 是 undefined,collection.item(0) 是 null。传入 '*' 可选择所有后代元素。请参阅 getElementsByTagName()。

{
  const paragraphs = document.getElementsByTagName('p');
  console.log(paragraphs.length);
  if (paragraphs.length > 1) {
    console.log(paragraphs[1].textContent);
  }
}

将查找范围限制在一个元素内

在元素上查找时不包含元素自身,但可以找到嵌套后代,例如第二个段落中的 strong。打开完整示例后,在控制台分别运行前两个代码片段。

{
  const group = document.querySelector('#group');
  if (group) {
    const local = group.getElementsByTagName('p');
    const second = local[1];
    if (second) {
      const strong = second.getElementsByTagName('strong')[0];
      console.log(strong?.textContent);
    }
  }
}

比较实时 HTMLCollection 与静态结果

添加或删除元素会更新集合长度和索引。如果向前遍历时删除元素,后面的索引会移动,可能漏掉一个结果。可以反向遍历,或先用 Array.from() 复制集合。

{
  const group = document.querySelector('#group');
  const live = group.getElementsByTagName('p');
  const snapshot = Array.from(live);

  const added = document.createElement('p');
  added.textContent = '新段落';
  group.append(added);
  console.log(live.length);    
  console.log(snapshot.length);
}

querySelectorAll('p') 返回静态 NodeList。它与 Array.from() 生成的数组一样保留查询时的成员。两者仍引用原始元素,因此可以读到修改后的文本。请参阅 querySelectorAll()。

运行完整的段落示例

将完整示例以 UTF-8 保存为 tag-name-example.html 并打开。区段外有一个段落,内部有两个。第二个段落包含 strong。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>按标签收集元素</title>
</head>
<body>
<h1>收集段落</h1>
<p>区段外的段落</p>
<section id="group">
  <p>第一个段落</p>
  <p><strong>第二个</strong>段落</p>
</section>
<button id="add" type="button">添加段落</button>
<button id="reset" type="button">重置</button>
<pre id="output" aria-live="polite"></pre>
<script>
const group = document.querySelector('#group');
const allParagraphs = document.getElementsByTagName('p');
const groupParagraphs = group.getElementsByTagName('p');
const initialArray = Array.from(groupParagraphs);
const initialNodes = group.querySelectorAll('p');
const output = document.querySelector('#output');

function show() {
  const second = groupParagraphs[1];
  const strong = second.getElementsByTagName('strong')[0];
  output.textContent = `文档中的 p: ${allParagraphs.length}\n区段中的 p: ${groupParagraphs.length}\n初始数组: ${initialArray.length}\n静态 NodeList: ${initialNodes.length}\n第二个段落: ${second.textContent.trim()}\n强调文本: ${strong.textContent}`;
}

document.querySelector('#add').addEventListener('click', () => {
  const paragraph = document.createElement('p');
  paragraph.textContent = `新增段落 ${groupParagraphs.length + 1}`;
  group.append(paragraph);
  show();
});
document.querySelector('#reset').addEventListener('click', () => {
  while (groupParagraphs.length > initialArray.length) {
    groupParagraphs[groupParagraphs.length - 1].remove();
  }
  show();
});
show();
</script>
</body>
</html>

文档和区段的初始段落数为 3 和 2。添加一个段落后分别变为 4 和 3,而数组和静态列表仍为 2。强调文本保持不变。重置会删除添加的段落。