CKTIS / JavaScript
document.querySelector — the first matching element
document.querySelector(selectors) finds the first element matching a CSS selector. It returns an element or null; an invalid selector throws 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
document.querySelector(selectors)document.querySelector(selectors) is a DOM method, not part of ECMAScript itself. It accepts a CSS selector string and returns the first matching Element in document tree order, or null.
Check for null before reading properties of the result. Invalid selector syntax throws a DOMException named SyntaxError rather than returning null. For a comma-separated selector list, element tree order determines the result, not selector order.
In contrast, querySelectorAll() returns a static list of all matches. The example calls querySelector() on the current page’s document, so which elements match depends on that page’s HTML markup.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Document.querySelector</title>
</head>
<body>
<h1>First matching element</h1>
<ul>
<li class="item">First</li>
<li class="item">Second</li>
</ul>
<script>
console.log(document.querySelector('.item').textContent);
console.log(document.querySelector('.missing') === null);
try {
document.querySelector('[');
} catch (error) {
console.log(error.name);
}
</script>
</body>
</html>Result
First true SyntaxError
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.