Selecting an Element
Use querySelector and querySelectorAll to select DOM elements with CSS-style selectors. Target elements by id, class, tag, and attribute.
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.
Returns the first matching element, or null if none found:
document.querySelector("#header"); // by iddocument.querySelector(".card"); // by classdocument.querySelector("button"); // by tagdocument.querySelector("[data-active]"); // by attributedocument.querySelector(".nav a.active"); // by complex selectorAny CSS selector works. That’s the point — you already know the syntax.
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.
You can query within an element instead of the entire document:
const nav = document.querySelector(".nav");const links = nav.querySelectorAll("a"); // only links inside .navgetElementById is older and only works with IDs. querySelector does everything. Use querySelector — it’s more consistent and flexible.
// Old waydocument.getElementById("header");
// New way — same resultdocument.querySelector("#header");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 nullCheck first if the element might not exist:
const el = document.querySelector(".might-not-exist");el?.classList.add("active"); // optional chaining — safe