querySelector
Learn to select the first matching element with a CSS selector.
Using a CSS selector with querySelector
querySelector takes a CSS selector and returns the first matching element. Unlike getElementById, it also works with classes, tags and more complex selectors, not just ids.
Examples:
document.querySelector("#save") — element with id save.document.querySelector(".btn") — first element with class btn.document.querySelector("p") — first <p> tag.
The leading # or . signs must be written; they cannot be skipped like in getElementById.
Common selectors
querySelector accepts any valid CSS selector. The most common ones are:
#id — by id attribute..class — by class attribute.tag — by tag name..parent .child — an element inside a specific container.
If the selector does not match, it returns null; just like with getElementById. So it is a good habit to check the result before using it.
Exercise Update the heading
Select the first element with class "title" using querySelector and assign it to heading. Then set heading.textContent to "Application".
Show example solution
Select with querySelector('.title'), then write heading.textContent = 'Application'.
Example solution:
const heading = document.querySelector(".title");
heading.textContent = "Application";
Test yourself
-
Select the first element with class 'btn'
- querySelector("#btn")
- querySelector("btn")
- querySelector("*btn")
- querySelector(".btn")
Show answer
querySelector(".btn") — Correct! Class selectors start with the . sign.
-
Call with a class selector
// Select the first element with class "active" const active = document.____;Show answer
// Select the first element with class "active" const active = document.querySelector('.active'); -
Match each selector to its meaning
- #save
- element with id save
- .btn
- element with class btn
- p
- element representing a p tag
- .card .title
- title inside the card class
-
What does querySelector return if there is no match?
- null
- undefined
- An empty string ("")
- It throws an error
Show answer
null — Correct! It returns null when there is no match.