Selecting Elements
Before you can read or change anything in the DOM, you need to
select the element you want to work with. JavaScript provides several
methods — getElementById,
querySelector,
querySelectorAll and more — each suited to
different scenarios. Master these and the entire DOM becomes yours to control.
The DOM Tree — A Quick Recap
The browser parses your HTML and builds a Document Object Model (DOM) — a tree of nodes. Each HTML tag becomes an Element node. Selecting elements means traversing this tree to find the node you want:
id attribute.
The fastest selector — direct hash-map lookup by the browser.getElementById
document.getElementById(id) is the
oldest and fastest selector. It looks up the element whose id attribute exactly
matches the string you pass. Since IDs must be unique in a document, it always returns at most
one element:
const btn = document.getElementById("submitBtn");
// Returns the Element, or null if not found
if (btn) {
btn.textContent = "Clicked!";
}
// ── Basic usage ─────────────────────────────────────────────
const header = document.getElementById("main-header");
console.log(header); // <h1 id="main-header">...</h1>
// ── Always guard against null ────────────────────────────────
const modal = document.getElementById("loginModal");
if (modal) {
modal.style.display = "block";
}
// ── Common mistake — do NOT add # ────────────────────────────
document.getElementById("#myId"); // ❌ WRONG — returns null
document.getElementById("myId"); // ✅ RIGHT
// ── Read content ────────────────────────────────────────────
const title = document.getElementById("page-title");
console.log(title.textContent); // "Welcome to K2infocom"
console.log(title.innerHTML); // raw HTML string including tags
getElementById does not use a # prefix — unlike CSS.
Passing "#myId" will always return null. Only
querySelector("#myId") uses the CSS hash-prefix syntax.
querySelector
querySelector(selector) accepts
any valid CSS selector — IDs, classes, attributes, pseudo-classes, combinators
—
and returns the first matching element in document order. It is the most
versatile single-element picker:
".card"
// ── By ID (same as getElementById but with #) ────────────────
const hero = document.querySelector("#hero-section");
// ── By class name ────────────────────────────────────────────
const firstCard = document.querySelector(".card");
// ── By tag ───────────────────────────────────────────────────
const firstPara = document.querySelector("p");
// ── Attribute selector ───────────────────────────────────────
const emailInput = document.querySelector('input[type="email"]');
// ── Combinator — child inside a parent ───────────────────────
const navLink = document.querySelector("nav .nav-link.active");
// ── Scoped search — search inside an element ─────────────────
const form = document.querySelector("#loginForm");
const submitBtn = form?.querySelector('button[type="submit"]');
// ↑ searches ONLY inside #loginForm — not the whole document
// ── Pseudo-class ─────────────────────────────────────────────
const lastItem = document.querySelector("li:last-child");
const checked = document.querySelector('input:checked');
querySelector and querySelectorAll on
any element, not just document. This restricts the search to
descendants of that element — a powerful pattern to avoid accidental matches elsewhere on the
page.
querySelectorAll & NodeList
querySelectorAll(selector) returns a
static NodeList — a snapshot of all matching elements at the time of the call.
It never returns null; if nothing matches, you get an empty NodeList. Use
forEach, for...of, or spread it into an array:
// ── Select all <li> elements ─────────────────────────────────
const items = document.querySelectorAll("li");
console.log(items.length); // number of <li> tags
// ── Iterate with forEach ──────────────────────────────────────
items.forEach(item => {
item.style.color = "#f7df1e";
});
// ── Iterate with for...of ─────────────────────────────────────
for (const item of items) {
console.log(item.textContent);
}
// ── Convert to Array for full array methods ───────────────────
const arr = [...items]; // spread into real Array
const texts = arr.map(el => el.textContent);
// ── Multiple selectors separated by comma ─────────────────────
const mixed = document.querySelectorAll("h2, h3, .highlight");
// ↑ selects all h2, h3 and .highlight elements in one call
// ── Empty NodeList check ──────────────────────────────────────
const missing = document.querySelectorAll(".nonexistent");
console.log(missing.length); // 0 — never null
getElementsByClassName & getElementsByTagName
These older methods return a live HTMLCollection — a
collection that automatically updates when the DOM changes. They are faster in simple cases
but less flexible than querySelectorAll:
// ── getElementsByClassName — no dot prefix ───────────────────
const cards = document.getElementsByClassName("card");
// ↑ pass the class name WITHOUT a leading dot
console.log(cards[0]); // first .card element
// ── Live collection — updates automatically! ─────────────────
const paras = document.getElementsByTagName("p");
console.log(paras.length); // e.g. 5
document.body.appendChild(document.createElement("p"));
console.log(paras.length); // 6 — live! updated automatically
// ── HTMLCollection doesn't have forEach — convert first ───────
const btnList = document.getElementsByTagName("button");
Array.from(btnList).forEach(btn => {
btn.setAttribute("aria-label", "button");
});
// ── Scoped on an element ─────────────────────────────────────
const nav = document.querySelector("nav");
const navLinks = nav.getElementsByTagName("a");
// ↑ searches only inside <nav>
getElementsBy*) is live — it
reflects DOM changes instantly.
NodeList from querySelectorAll is static — it is a
snapshot
taken at the time of the call. For most tasks, a static NodeList is safer and easier to reason
about.
Selector Methods — Comparison
Here is a quick reference to help you choose the right method for each situation:
| Method | Selector Syntax | Returns | Live? | Best For |
|---|---|---|---|---|
| getElementById() | id string — no # | Element | null | — | Fast single-element by id |
| querySelector() | Any CSS selector | Element | null | No | First flexible CSS match |
| querySelectorAll() | Any CSS selector | NodeList (static) | No | All matches, any selector |
| getElementsByClassName() | class name — no dot | HTMLCollection (live) | Yes | Class-based live list |
| getElementsByTagName() | tag name string | HTMLCollection (live) | Yes | All tags of a type |
| getElementsByName() | name attribute value | NodeList (live) | Yes | Form inputs by name |
DOM Traversal — Navigating Relatives
Once you have a reference to an element, you can navigate the tree using traversal properties — no selector needed. This is useful when you already have one element and need a nearby relative:
const item = document.querySelector(".active-item");
// ── Parent ───────────────────────────────────────────────────
item.parentElement; // direct parent Element
item.closest(".container"); // nearest ancestor matching CSS selector
// ── Children ─────────────────────────────────────────────────
item.children; // live HTMLCollection of child Elements
item.firstElementChild; // first child Element (skips text nodes)
item.lastElementChild; // last child Element
item.childElementCount; // number of child Elements
// ── Siblings ─────────────────────────────────────────────────
item.nextElementSibling; // next sibling Element
item.previousElementSibling; // previous sibling Element
// ── closest() — walk up the tree until selector matches ──────
const btn = document.querySelector("button.delete");
const card = btn.closest(".card"); // the card wrapping the button
card?.remove(); // delete the whole card
element.closest(selector) walks up the ancestor chain until it finds a
match or reaches the document root. It is the key tool for event delegation —
attaching a single listener to a parent and detecting which child was clicked.
Real-World Use Cases
These are the everyday situations where DOM selection methods are the essential first step:
Try It — Live Editor
Experiment with DOM selectors below. The demo selects elements using different methods and displays the results — edit the HTML or the selectors and run again.
Common Patterns & Recipes
These are practical selection patterns you'll reach for constantly in real JavaScript projects:
// ── Safe selector with optional chaining ─────────────────────
const price = document.querySelector(".product-price")?.textContent;
// No error if .product-price doesn't exist — returns undefined
// ── Select all data-* elements and process ────────────────────
document.querySelectorAll("[data-tooltip]").forEach(el => {
const text = el.dataset.tooltip;
// attach tooltip behaviour...
});
// ── Find element by partial attribute value ───────────────────
const icons = document.querySelectorAll('[class*="icon-"]');
// matches class="icon-home", "icon-user", etc.
// ── Check if element matches a selector ──────────────────────
const el = document.querySelector(".btn");
if (el?.matches(".btn-primary")) {
console.log("Primary button!");
}
// ── Select n-th element directly ─────────────────────────────
const third = document.querySelector("tr:nth-child(3)");
// ── Bulk class toggle on all matching ─────────────────────────
document.querySelectorAll(".tab").forEach(t => t.classList.remove("active"));
document.querySelector(`[data-tab="${targetId}"]`)?.classList.add("active");
id="hero"
using getElementById?- getElementById(id) is the fastest selector — pass the id string without a
#prefix. Returns one Element or null. - querySelector(css) accepts any CSS selector and returns the first match in document order, or null if nothing matches.
- querySelectorAll(css) returns a static NodeList of all matches — iterate with forEach or spread into an array. Never returns null.
- getElementsByClassName / getElementsByTagName return a live HTMLCollection that updates automatically when the DOM changes.
- You can call
querySelectorandquerySelectorAllon any element to scope the search to that element's descendants. - Use traversal properties —
parentElement,children,nextElementSibling— to navigate relatives from a reference you already hold. - closest(css) walks up the ancestor chain and returns the first ancestor matching the selector — essential for event delegation.
- element.matches(css) returns a boolean — useful for checking if a selected element satisfies additional criteria.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.