Course contentsShow
← Web Development
Lesson 678 of 2,98212. The Document Object ModelFree lesson

document.querySelector()

Select the first element matching any CSS selector, the most flexible single-element selector.

Mastering the Swiss Army Knife of Element Selection

What you'll learn: How to select any single element on a page using CSS selector syntax — the most flexible and modern way to grab exactly what you need.


The Most Powerful Single-Element Selector

While getElementById(), getElementsByClassName(), and getElementsByTagName() each solve specific selection tasks, document.querySelector() is like having all of them — plus much more — in one tool. It accepts any valid CSS selector and returns the first matching element it finds in the document.

Think of it this way: if the DOM is a library, the previous methods let you search by "book with this exact ID number" or "all books with this color spine." querySelector() lets you ask complex questions like "the first mystery novel on the third shelf written by authors whose last name starts with 'K'."

How It Works

// By ID (just like getElementById, but with # symbol)
const header = document.querySelector('#main-header');

// By class (returns FIRST match only)
const button = document.querySelector('.btn-primary');

// By tag name
const paragraph = document.querySelector('p');

// Complex selectors (this is where it shines!)
const firstLinkInNav = document.querySelector('nav a');
const submitButton = document.querySelector('form button[type="submit"]');
const specialItem = document.querySelector('.list-item:first-child');

The key difference from getElementsByClassName() and getElementsByTagName()? Those return collections of elements. querySelector() returns only one element — the first match — or null if nothing matches.

Key Takeaway: document.querySelector() is your go-to method for selecting a single element using any CSS selector syntax, giving you maximum flexibility with familiar patterns.