Select the first element that matches a CSS selector with querySelector()

document.querySelector(selector) returns the first element in document order that matches a Cascading Style Sheets (CSS) selector. If nothing matches, it returns null. An invalid selector throws SyntaxError.

Select the first matching element

.target selects a class and #panel selects an ID. Read or change the element after checking it exists. Accessing a property on null throws. See querySelector().

const first = document.querySelector('.target');
if (first !== null) {
  first.textContent = 'First item';
}

Limit the search with a compound selector

#panel .target only matches descendants of the element with ID panel. If you already have that element, panel.querySelector('.target') searches its descendants. Use querySelectorAll() to get all matches. The single result from querySelector() does not take an array index.

const firstAnywhere = document.querySelector('.target');
const firstInPanel = document.querySelector('#panel .target');

console.log(firstAnywhere?.textContent);
console.log(firstInPanel?.textContent); 

Handle no match, invalid selectors, and special IDs

A valid selector can return null because no element matches yet. If the code runs before the relevant HTML is parsed, move it after that HTML or use defer on an external classic script. A malformed selector such as ??? throws even when the document is ready.

document.querySelector('.missing'); // null

try {
  document.querySelector('???');
} catch (error) {
  console.log(error.name); // 'SyntaxError'
}

An ID such as 2026:Q1 needs escaping when used in a selector. Escape the ID value with CSS.escape() and then add #. The example creates a section in memory and locates its child.

{
  const section = document.createElement('section');
  const item = document.createElement('p');
  const id = '2026:Q1';
  item.id = id;
  section.append(item);

  const selector = '#' + CSS.escape(id);
  console.log(section.querySelector(selector) === item); // true
}

The output is true. Escaping the entire selector would escape the # prefix as well. For a document-wide lookup by ID alone, document.getElementById(id) accepts the literal value. See CSS.escape().

Try the complete selection example

Save the full example in UTF-8 as query-selector-example.html and open it. Run the selectors one at a time. .target highlights the item outside the panel, and #panel .target highlights the first item inside. .missing displays null, while ??? displays SyntaxError. Reset restores the first selector and highlight.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>First CSS selector result</title>
  <style>.selected { background: #fff2a8; outline: 2px solid #a76b00; }</style>
</head>
<body>
<h1>Select the first element</h1>
<p class="target">Outside item</p>
<section id="panel">
  <p class="target">First panel item</p>
  <p class="target">Second panel item</p>
</section>
<label for="selector">CSS selector</label>
<select id="selector">
  <option value=".target">.target</option>
  <option value="#panel .target">#panel .target</option>
  <option value=".missing">.missing</option>
  <option value="???">???</option>
</select>
<button id="find" type="button">Find</button>
<button id="reset" type="button">Reset</button>
<p id="output" aria-live="polite"></p>
<script>
const choice = document.querySelector('#selector');
const output = document.querySelector('#output');

function choose() {
  document.querySelector('.selected')?.classList.remove('selected');
  try {
    const found = document.querySelector(choice.value);
    if (found === null) {
      output.textContent = 'No matching element: null';
      return;
    }
    found.classList.add('selected');
    output.textContent = `Selected: ${found.textContent.trim()}`;
  } catch (error) {
    if (error.name === 'SyntaxError') {
      output.textContent = 'Invalid CSS selector: SyntaxError';
    } else {
      throw error;
    }
  }
}

document.querySelector('#find').addEventListener('click', choose);
document.querySelector('#reset').addEventListener('click', () => {
  choice.value = '.target';
  choose();
});
choose();
</script>
</body>
</html>