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);
  }
}

特定の要素の中だけを探す

要素から検索しても、その要素自身は含まれません。2番目の段落内のstrongなど、入れ子になった子孫も探せます。完全なサンプルを開いて、最初の2つのコードをコンソールで個別に実行します。

{
  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として保存し、開きます。区間の外に段落が1つ、中に2つあります。2番目の段落はstrongを含みます。

<!doctype html>
<html lang="ja">
<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>2番目</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}\n2番目の段落: ${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です。1つ追加すると4と3になり、配列と静的な一覧は2のままです。強調テキストは変わりません。リセットで追加した段落を削除します。