JavaScript DOM Selection

DOM selection is how you get a reference to an HTML element so you can read or change it with JavaScript.

There are five selection methods:

  • document.getElementById()
  • document.querySelector()
  • document.querySelectorAll()
  • document.getElementsByClassName()
  • document.getElementsByTagName()

In most cases, prefer querySelector and querySelectorAll. They accept any CSS selector, so they are the most flexible.

I. Single element selectors

These return the first matching element, or null if nothing matches.

document.getElementById()

Selects one element by its id. Because IDs must be unique on a page, this always returns at most one element.

<h2 id="food">Favorite food</h2>
const heading = document.getElementById("food");
console.log(heading); // <h2 id="food">Favorite food</h2>

document.querySelector()

Accepts any CSS selector. Useful for IDs, classes, tags, attributes, or complex selectors.

document.querySelector("#todo");         // by ID
document.querySelector(".container");    // by class
document.querySelector("h2");            // by tag
document.querySelector("input[type=text]"); // by attribute

When multiple elements match, only the first is returned.

II. Multiple element selectors

These return all matching elements.

document.querySelectorAll()

Returns a NodeList of all matching elements. You can loop over it with forEach or for...of.

<ul class="items">
  <li class="item">Item 1</li>
  <li class="item">Item 2</li>
  <li class="item">Item 3</li>
</ul>
const items = document.querySelectorAll(".item");
console.log(items); // NodeList(3) [li.item, li.item, li.item]

items.forEach(item => console.log(item.textContent));
// Item 1
// Item 2
// Item 3

document.getElementsByClassName()

Returns an HTMLCollection of all elements with the given class name. Unlike NodeList, HTMLCollection does not have forEach. Convert it to an array first if you need to iterate.

const items = document.getElementsByClassName("item");
// HTMLCollection(3) [li.item, li.item, li.item]

// Convert to array to use forEach or map
const itemArray = Array.from(items);
itemArray.forEach(item => console.log(item.textContent));

document.getElementsByTagName()

Returns an HTMLCollection of all elements with the given tag name.

const listItems = document.getElementsByTagName("li");
console.log(listItems); // HTMLCollection of all <li> elements

III. Choosing the right method

GoalMethod
Select by IDgetElementById or querySelector("#id")
Select one element by class/tag/attributequerySelector
Select all elements matching a CSS selectorquerySelectorAll
Needs live updates as DOM changesgetElementsByClassName or getElementsByTagName

querySelectorAll returns a static snapshot. getElementsByClassName and getElementsByTagName return live collections that update automatically when the DOM changes.