Select one element
Quick answer
querySelector returns the first matching element in the search scope or null. Use valid CSS selector syntax and handle absence before accessing properties.
Browser example
Run in a browser document, not a bare Node.js process.
const root=document.createElement("div"); const p=document.createElement("p"); p.className="note";root.append(p); console.log(root.querySelector(".note")===p,root.querySelector(".missing")===null);Expected console output:
true trueCommon mistake
An absent match is null, not an empty element.
Practice
Create two paragraphs and select the first using a class.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select one element — Knowledge Check
Check the central concept, apply it to a new scenario, and predict browser behavior.
What does querySelector return when nothing matches?
Two descendants match the selector .item. Which does querySelector return?
What should you check before reading textContent from a query result that may be absent?
You call panel.querySelector('.note'). A note exists outside panel but none within it. What is returned?
What is printed by this browser snippet? (Select one element)
const p=document.createElement("div");const a=document.createElement("p"),b=document.createElement("p");a.className=b.className="item";a.textContent="first";b.textContent="second";p.append(a,b);console.log(p.querySelector(".item").textContent);