DOM Selecting Elements
Before you can change an element, you have to find it. The DOM offers several methods for that. Two of them — querySelector and querySelectorAll — accept any CSS selector and cover almost every need; the older getElementBy… methods are still common and slightly faster for simple cases.
The selection methods
| Method | Returns | Example |
|---|---|---|
document.getElementById(id) |
one element or null |
getElementById("menu") |
document.querySelector(css) |
the first match or null |
querySelector(".card > h2") |
document.querySelectorAll(css) |
a static NodeList of all matches |
querySelectorAll("li.done") |
document.getElementsByClassName(name) |
a live HTMLCollection |
getElementsByClassName("item") |
document.getElementsByTagName(tag) |
a live HTMLCollection |
getElementsByTagName("p") |
element.closest(css) |
nearest ancestor (or itself) that matches | btn.closest(".card") |
By id and by CSS selector
<h1 id="main-title">Fruit shop</h1>
<ul class="products">
<li class="fruit">Apple</li>
<li class="fruit sale">Banana</li>
<li class="fruit">Cherry</li>
<li class="fruit sale">Date</li>
</ul>
<script>
const title = document.getElementById("main-title"); // no "#" here!
console.log(title.textContent);
const firstFruit = document.querySelector(".fruit");
console.log("first:", firstFruit.textContent);
const firstSale = document.querySelector("li.sale");
console.log("first on sale:", firstSale.textContent);
const third = document.querySelector(".products li:nth-child(3)");
console.log("third:", third.textContent);
console.log("missing:", document.querySelector(".vegetable")); // null
</script>querySelector uses exactly the same selectors as CSS: #id, .class, tag, [attribute], descendant (a b), child (a > b), pseudo-classes like :first-child or :checked, and comma-separated lists.
Selecting many elements
querySelectorAll returns a NodeList. It has a length, can be indexed, supports forEach and for…of, and can be converted to a real array for map/filter:
<ul>
<li class="task done">Buy milk</li>
<li class="task">Write report</li>
<li class="task done">Call Sam</li>
<li class="task">Book flights</li>
</ul>
<p id="summary"></p>
<script>
const tasks = document.querySelectorAll(".task");
console.log("tasks:", tasks.length);
tasks.forEach((li, i) => console.log(i, li.textContent));
const doneNames = [...document.querySelectorAll(".task.done")].map((li) => li.textContent);
console.log("done:", doneNames);
for (const li of document.querySelectorAll(".task:not(.done)")) {
li.style.fontWeight = "bold";
}
document.getElementById("summary").textContent =
`${doneNames.length} of ${tasks.length} tasks done`;
</script>Searching inside an element
All querySelector… methods also exist on elements, searching only within that element. And closest() walks up the tree — perfect for finding the card or row that a clicked button belongs to:
<style>
.card { border: 1px solid #ccc; border-radius: 8px; padding: 8px 12px; margin: 6px 0; }
.card.picked { background: #fff6d6; }
</style>
<div class="card" data-id="1"><h3>Plan A</h3><button>Pick</button></div>
<div class="card" data-id="2"><h3>Plan B</h3><button>Pick</button></div>
<div class="card" data-id="3"><h3>Plan C</h3><button>Pick</button></div>
<script>
for (const button of document.querySelectorAll(".card button")) {
button.addEventListener("click", () => {
const card = button.closest(".card"); // the card containing this button
const name = card.querySelector("h3").textContent;
document.querySelectorAll(".card").forEach((c) => c.classList.remove("picked"));
card.classList.add("picked");
console.log(`picked ${name} (id ${card.dataset.id})`);
});
}
</script>Static vs live collections
A NodeList from querySelectorAll is a snapshot — it doesn't change when the page changes. An HTMLCollection from getElementsByClassName/getElementsByTagName (and element.children) is live — it updates automatically:
<div id="box"><p>one</p></div>
<script>
const box = document.getElementById("box");
const staticList = box.querySelectorAll("p");
const liveList = box.getElementsByTagName("p");
box.append(document.createElement("p"));
console.log("static NodeList:", staticList.length); // still 1
console.log("live HTMLCollection:", liveList.length); // now 2
</script>Navigating the tree
Once you have an element, you can move to its relatives:
| Property | Gives |
|---|---|
parentElement |
the parent element |
children |
child elements (live HTMLCollection) |
firstElementChild / lastElementChild |
first / last child element |
nextElementSibling / previousElementSibling |
neighbouring elements |
childNodes, firstChild, nextSibling |
same, but including text and comment nodes |
Tip:
getElementByIdandquerySelectorreturnnullwhen nothing matches. Calling a method onnullthrows "Cannot read properties of null". If an element might be missing, check first or use optional chaining:document.querySelector(".banner")?.remove().
Test yourself
What does document.querySelector(".item") return when several elements match?
- All of them
- The first one
- The last one
- null
Which call correctly selects the element with id cart?
- getElementById("#cart")
- querySelector("cart")
- querySelector("#cart")
- querySelectorAll(".cart")
Which method finds the nearest ancestor matching a selector?
- parentElement
- closest()
- querySelector()
- matches()