Skip to content
blog
2 min read

Selecting an Element

Use querySelector and querySelectorAll to select DOM elements with CSS-style selectors. Target elements by id, class, tag, and attribute.

Before you can manipulate an element, you need to select it. querySelector and querySelectorAll are the modern way to do this.

querySelector

Returns the first matching element, or null if none found:

document.querySelector("#header"); // by id
document.querySelector(".card"); // by class
document.querySelector("button"); // by tag
document.querySelector("[data-active]"); // by attribute
document.querySelector(".nav a.active"); // by complex selector

Any CSS selector works. That’s the point — you already know the syntax.

querySelectorAll

Returns all matching elements as a NodeList:

const cards = document.querySelectorAll(".card");
cards.forEach((card) => {
card.style.opacity = "0.5";
});

NodeList looks like an array and supports forEach, but it isn’t a full array. Use Array.from(cards) if you need array methods like map or filter.

Scoped Queries

You can query within an element instead of the entire document:

const nav = document.querySelector(".nav");
const links = nav.querySelectorAll("a"); // only links inside .nav

querySelector vs. getElementById

getElementById is older and only works with IDs. querySelector does everything. Use querySelector — it’s more consistent and flexible.

// Old way
document.getElementById("header");
// New way — same result
document.querySelector("#header");

What to Do When null

If querySelector returns null and you try to call methods on it, you get an error:

const el = document.querySelector(".missing");
el.classList.add("active"); // TypeError: Cannot read properties of null

Check first if the element might not exist:

const el = document.querySelector(".might-not-exist");
el?.classList.add("active"); // optional chaining — safe