01 / 21

Selecting
DOM Elements

Learn how to find and grab any HTML element on a page using JavaScript's powerful querySelector and querySelectorAll methods.

JavaScript

What is the DOM?

The Document Object Model (DOM) is a tree-like representation of your HTML page that JavaScript can read and modify. Every HTML tag becomes a node in this tree: the page is the root, and each element is a branch or leaf.

document <html> <head> <body> <h1> <div>

Why Select Elements?

Before you can do anything interactive on a web page, you must first grab a reference to the element you want to work with. Selection is the first step in virtually every DOM operation.

Read Content
Get the text or HTML inside an element to display elsewhere or validate.
Change Styles
Toggle classes, modify colors, or show/hide elements dynamically.
Listen for Events
Attach click, hover, or keyboard handlers to make pages interactive.

CSS Selectors Refresher

Both querySelector and querySelectorAll accept the exact same selector strings you already use in CSS. Here are the three most common types:

Tag
"p" selects all <p> elements on the page.
Class
".btn" selects elements with class="btn".
ID
"#main" selects the single element with id="main".

The querySelector Method

const element = document.querySelector(".hero-title");
1
Returns one element: the first element in the DOM that matches the selector string.
2
Returns null if no element matches, so always check before using.
3
Accepts any valid CSS selector: tags, classes, IDs, attribute selectors, combinators.

The querySelectorAll Method

const items = document.querySelectorAll("li.active");
1
Returns a NodeList of all matching elements, not just the first one.
2
NodeList is array-like: you can use .length, index with [0], and iterate with forEach.
3
Returns an empty NodeList (length 0) if nothing matches: never null.

querySelector vs querySelectorAll

querySelector querySelectorAll
Returns Single Element (or null) NodeList (array-like)
How many? First match only All matches
No match null Empty NodeList (length 0)
forEach? No (single object) Yes (iterable)
Use when You need one element You need a group

How the Browser Searches

document <body> <div.container> <footer> <p.intro> <p.detail> <p.intro> ★ 1st match 2nd match querySelector(".intro") → 1st match only

The browser walks the DOM tree in depth-first order (top to bottom, left to right). querySelector stops at the first match. querySelectorAll collects all matches into a NodeList.

How to Apply It

1
Identify the element you need: is it unique (ID) or one of many (class, tag)?
2
Write the CSS selector that targets it: "#nav", ".card", "ul > li".
3
Choose the method: querySelector for one, querySelectorAll for many.
4
Store the result in a const variable for reuse.
5
Act on it: change text, toggle classes, add event listeners, etc.

Example 1: Select by ID

Given this HTML, select the main heading and change its text:

// HTML: <h1 id="title">Hello</h1> const heading = document.querySelector("#title"); heading.textContent = "Welcome!";

Example 2: Select by Class

Highlight every element with class "highlight":

// HTML: <p class="highlight">A</p> // <p class="highlight">B</p> // <p>C</p> const items = document.querySelectorAll(".highlight"); items.forEach(function(el) { el.style.backgroundColor = "yellow"; });

Example 3: Complex Selectors

Select only the <a> tags inside a <nav> that have a specific data attribute:

const navLinks = document.querySelectorAll( "nav a[data-active='true']" ); navLinks.forEach(function(link) { link.classList.add("active-link"); });

Example 4: Scoped Selection

You can call querySelector on any element, not just document, to search only within that element's subtree:

const sidebar = document.querySelector("#sidebar"); const firstLink = sidebar.querySelector("a"); firstLink.textContent = "Home";

NodeList vs HTMLCollection

Older methods like getElementsByClassName return an HTMLCollection, which behaves differently from the NodeList returned by querySelectorAll:

NodeList HTMLCollection
From method querySelectorAll getElementsByClassName
forEach ✓ Yes ✕ No
Live updates? Static (snapshot) Live (auto-updates)
Selector power Any CSS selector Class or tag only

Common Mistakes

✕ Forgetting the dot or hash
Writing querySelector("btn") selects a <btn> tag (which doesn't exist). Use ".btn" for classes, "#btn" for IDs.
✕ Using forEach on querySelector
querySelector returns a single element, not a list. Calling .forEach() on it throws a TypeError. Use querySelectorAll when you need to iterate.
✕ Running before DOM loads
If your script runs in the <head> before the HTML is parsed, elements haven't been created yet. Place scripts at the end of <body> or use defer.

Selection Methods Summary

Method Returns Best For
querySelector Element or null Single, unique element
querySelectorAll Static NodeList Multiple elements
getElementById Element or null By ID (legacy)
getElementsByClassName Live HTMLCollection By class (legacy)
getElementsByTagName Live HTMLCollection By tag (legacy)

Question 1 of 5

What does document.querySelector(".card") return if the page has three elements with the class "card"?

Question 2 of 5

Which selector string correctly targets an element with id="main-nav"?

Question 3 of 5

What happens when document.querySelector("#missing") finds no matching element on the page?

Question 4 of 5

You need to add an event listener to every <button> with class "delete-btn" on the page. Which approach is correct?

Question 5 of 5

What is the advantage of calling querySelector on a specific parent element instead of on document?