Web Analytics

Selecting Elements

Beginner ~15 min read

The Document Object Model (DOM)

The DOM is a tree-like representation of your HTML document. JavaScript uses the DOM to access and manipulate HTML elements.

Selecting by ID

The most common way to access an HTML element is to use the id of the element.

document.getElementById("myId");
HTML
CSS
JS

Selecting by Class Name

You can find all elements with the same class name using getElementsByClassName. This returns an HTMLCollection (array-like object).

HTML
CSS
JS

Query Selectors

The querySelector() and querySelectorAll() methods allow you to use CSS selectors to find elements. This is very powerful and flexible.

  • querySelector(selector): Returns the first matching element.
  • querySelectorAll(selector): Returns a NodeList of all matching elements.
HTML
CSS
JS
NodeList vs HTMLCollection: querySelectorAll returns a NodeList, which has a built-in forEach() method. getElementsByClassName returns an HTMLCollection, which does NOT have forEach() (you have to use a regular for loop or convert it to an array).

Summary

  • getElementById is the fastest way to select a single element.
  • querySelector uses CSS syntax to find the first match.
  • querySelectorAll finds all matches and returns a NodeList.

Quick Quiz

Which method returns a NodeList?

A
getElementById
B
getElementsByClassName
C
querySelectorAll
D
querySelector