JavaScript: querySelector

querySelector() returns the first element that matches a CSS selector, making it useful for precise DOM lookups.

What you will learn

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