Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Element.querySelector — first matching descendant

Element.querySelector finds the first descendant matching a CSS selector. It returns an element or null; an invalid selector causes an exception.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

element.querySelector(selectors)

Element.querySelector accepts a selectors string containing a CSS selector or comma-separated selector list. It returns the first matching descendant in tree order, not selector-list order. The element on which it is called is not itself a result.

No match produces null. Check the result before accessing properties. Invalid selector syntax throws a DOMException named SyntaxError, rather than returning null.

Use :scope > .action to select a direct child. Without :scope, selector matching can consider ancestors outside the calling element, although the result remains its descendant. querySelectorAll() returns a static list of all matches instead of one element.

This is a DOM-standard API, not an ECMAScript language feature. The example requires a browser environment with a DOM; Node 24 being present in a repository does not establish support for this API.

Examples

const root = document.createElement('section');
const first = document.createElement('button');
const second = document.createElement('button');
first.className = 'action';
second.className = 'action';
first.textContent = 'First';
second.textContent = 'Second';
root.append(first, second);

console.log(root.querySelector('.action').textContent);
console.log(root.querySelector(':scope > .action') === first);
console.log(root.querySelector('.missing') === null);

Result

First
true
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources