Select and loop over matching elements with querySelectorAll()

querySelectorAll() returns a static NodeList of elements that match a Cascading Style Sheets (CSS) selector, in document order. If nothing matches, the list is empty. Query again to include nodes that start matching later.

Read all matching elements

Use length to count results and [0] for the first element. An invalid selector such as ??? throws SyntaxError, while a valid selector without matches returns a list of length 0. See 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
}

Loop over a NodeList and convert it to an array

Use forEach() to act on each node. Use Array.from(items) if you need array methods such as map(), or pass a mapping function directly to Array.from(). To return only the first match, see 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);
}

Select direct children or combine selectors

An element query for .item can match deeply nested descendants. Use :scope > .item to select only children of the element you called the method on. A comma joins alternatives, and each matching element occurs once even if it matches both. See :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']
}

Run the example in the browser console. The first result is ['direct', 'nested'] in document order, even though .warning comes first in the selector. The second result is just ['direct'].

Query again after the document changes

An earlier list keeps the same members after you add or remove elements. It still references those nodes, so changes to their text remain visible. For the snippet below, open the complete example first. Query again to reflect the added element.

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

Try a complete example with a changing list

Save the complete HTML as query-selector-all-example.html in UTF-8 and open it. Add an item to change the new count from 2 to 3 while the initial count stays at 2. Mark the current items and confirm all three are selected. Reset removes additions and highlights, returning the counts to 2, 2, and 0.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Compare querySelectorAll results</title>
  <style>.selected { background: #fff2a8; }</style>
</head>
<body>
<h1>Find all matching elements</h1>
<ul id="list">
  <li class="item">First item</li>
  <li class="item">Second item</li>
</ul>
<button id="add" type="button">Add item</button>
<button id="mark" type="button">Highlight current items</button>
<button id="reset" type="button">Reset</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 query: ${initial.length}\nNew query: ${current.length}\nHighlighted items: ${selected.length}`;
}

document.querySelector('#add').addEventListener('click', () => {
  const item = document.createElement('li');
  item.className = 'item added';
  item.textContent = `Added item ${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>