querySelector() (JavaScript)

document.querySelector() finds the first element on the page that matches a CSS selector. It is the standard way to grab an element so JavaScript can work with it.

JavaScript

Pass any CSS selector string — a tag name, .class, #id, or a combination — and querySelector returns the first match or null if nothing matches.

Use querySelectorAll() when you need every matching element as a list.

Syntax

document.querySelector(cssSelector)

Examples

JavaScript

const button = document.querySelector("#submit");
console.log(button.tagName);

Output:

BUTTON

Learn it in a lesson

See also

Back to the Dictionary