DOM Selection
querySelector & querySelectorAll
JavaScript
// querySelector — returns FIRST matching element (or null) const title = document.querySelector("h1"); const btn = document.querySelector(".btn-primary"); const nav = document.querySelector("#main-nav"); const first = document.querySelector("ul > li:first-child"); // querySelectorAll — returns NodeList of ALL matches const cards = document.querySelectorAll(".card"); const links = document.querySelectorAll("nav a"); // Convert NodeList to Array for full array methods const cardArray = [...cards]; const hrefs = [...links].map(link => link.href);
Older Methods (still useful)
JavaScript
// By ID — fastest, returns single element const form = document.getElementById("signup-form"); // By class name — returns HTMLCollection (live) const items = document.getElementsByClassName("menu-item"); // By tag name const paragraphs = document.getElementsByTagName("p"); // Prefer querySelector/querySelectorAll — more flexible
Scoped Queries
JavaScript
// Search within a specific element — not the whole document const nav = document.querySelector("nav"); const navLinks = nav.querySelectorAll("a"); // only links inside nav const sidebar = document.querySelector(".sidebar"); const heading = sidebar.querySelector("h2"); // first h2 in sidebar
DOM Traversal
JavaScript
const item = document.querySelector(".active"); // Navigate relative to an element item.parentElement // parent element item.children // all direct children (HTMLCollection) item.firstElementChild // first child item.lastElementChild // last child item.nextElementSibling // next sibling item.previousElementSibling // previous sibling // closest — traverse UP to find matching ancestor const card = item.closest(".card");
Checking Elements
JavaScript
const el = document.querySelector(".menu"); el.matches(".menu.open") // true if el matches selector el.contains(anotherEl) // true if el contains anotherEl // Always check if element exists before using it const modal = document.querySelector("#modal"); if (modal) { modal.style.display = "block"; }