document. querySelector()
Returns the first element that matches a CSS selector, or null when nothing matches.
- Returns
- The first matching element, or
null.
Example
#const first = document.querySelector('.task')
const todo = document.querySelector('.task:not(.done)')
const last = document.querySelector('.tasks li:last-child')
console.log(first)
console.log(todo.textContent)
console.log(last.textContent)
console.log(document.querySelector('.missing'))Definition and usage
#The querySelector() method searches the document and returns the first element that matches the given CSS selector. You can use any selector you know from stylesheets: "#menu", ".card", "nav a", "input[type=email]", or "li:last-child".
If no element matches, the method returns null. Reading a property from null throws an error, so for elements that might not be on the page, check the result or use the ?. operator.
You can call the method not only on document, but on any element too. Then it only searches inside that element, which is handy for repeating page fragments, such as course cards. To get every matching element, use querySelectorAll().
Syntax
#document.querySelector(selectors)
element.querySelector(selectors)Parameters
#selectors
string
A CSS selector, e.g."#menu"or".card h3". Separate multiple selectors with commas.
More examples
#const cssCard = document.querySelector('#css-course')
const price = cssCard.querySelector('.price')
console.log(cssCard)
console.log(price.textContent)const banner = document.querySelector('.promo-banner')
console.log(banner?.textContent ?? 'No banner on the page')
console.log(document.querySelector('#save').textContent)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Check the result before using it, or use
?.. A typo in the selector ends in a “Cannot read properties of null” error. - Search inside a specific element (
card.querySelector()) when the page has many similar fragments. - An id that starts with a digit needs special escaping in a selector. In that case, it’s simpler to use
getElementById().
Related entries
#- querySelector() vs getElementById()querySelector() accepts any CSS selector and returns the first matching element, while getElementById() only searches by the id attribute, but is simpler.
- document.querySelectorAll()Returns a static list (NodeList) of every element that matches a CSS selector.
- document.getElementById()Returns the element with the given identifier (the id attribute), or null when there isn’t one.
- Element.closest()Returns the nearest ancestor (or the element itself) matching a CSS selector, or null.
- ?.The ?. (optional chaining) operator safely reads a property. When the object is null or undefined, it returns undefined instead of throwing.
- Node.textContentReads or sets all of an element’s text, without HTML markup.
Spotted a mistake or missing an example? Write to us.