Syntax
document.getElementById(id)
document.querySelector(selector)
document.querySelectorAll(selector)Examples
getElementById() and querySelector()
Finding a single element two different ways.
const byId = document.getElementById("header");
const bySelector = document.querySelector("#header"); // equivalent, but more flexible
const firstButton = document.querySelector("button");
const specificClass = document.querySelector(".btn-primary");
const nested = document.querySelector("nav .menu-item.active");querySelectorAll() and Looping
Selecting multiple elements and iterating over them.
const items = document.querySelectorAll(".list-item");
console.log(items.length); // number of matches
items.forEach(item => {
console.log(item.textContent);
});
// NodeList supports forEach directly, but is NOT a real array
// use Array.from(items) if you need map/filter/etc.Best practices
- Use querySelector()/querySelectorAll() for their flexibility with any valid CSS selector, rather than mixing several older, more specific methods
- Use getElementById() when selecting by a known unique ID - it is marginally faster and communicates clear intent
- Remember querySelectorAll() returns a static NodeList - it does not update automatically if the DOM changes afterward
- Convert a NodeList to a real array with Array.from() if you need array methods like map() or filter() on the results
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification