JavaScript: querySelector
querySelector() returns the first element that matches a CSS selector, making it useful for precise DOM lookups.
What you will learn
- How to select by element, class, or attribute
- How to handle a selector with no match
- When to use querySelectorAll instead
Minimal example
const button = document.querySelector('.save-button');
if (button) {
button.textContent = 'Save';
}The selector uses CSS syntax. If no element matches, the result is null, so check it before reading or changing the element.
Common mistakes
- Remember that only the first matching element is returned.
- Use
querySelectorAllfor a collection and loop through the matches. - Escape or construct user-controlled selector values carefully; prefer a stable data attribute when appropriate.