JavaScriptのquerySelectorAll()で要素を選んで反復処理する

querySelectorAll()はCSS(カスケーディングスタイルシート)セレクターに一致する全要素を文書順に含む静的なNodeListを返します。一致がなければ空です。後から追加された要素を含めるには再検索します。

一致するすべての要素を読む

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)で配列にするか、変換関数をArray.from()に渡します。最初の1件だけなら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を使います。コンマは条件を組み合わせ、両方に合う要素も1回だけ含まれます。: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が先でも、第1の結果は文書順の['direct', 'nested']です。第2の結果は['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);
}

変化する一覧の完全な例を試す

UTF-8のquery-selector-all-example.htmlとして保存し、開きます。1件追加すると初回は2のまま、再検索は3です。現在の要素を強調して3件すべてを確認します。リセットすると2、2、0に戻ります。

<!doctype html>
<html lang="ja">
<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">2番目の項目</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>