Codectionary / Developer documentation / JavaScript

DOM Selection: querySelector(), getElementById()

These methods find elements in the DOM. getElementById() finds a single element by its unique id, generally the fastest option. querySelector() finds the first element matching any valid CSS selector, and querySelectorAll() returns all matching elements as a static NodeList.

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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation