Selecting Elements
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");
Selecting by Class Name
You can find all elements with the same class name using
getElementsByClassName. This returns an HTMLCollection
(array-like object).
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.
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
getElementByIdis the fastest way to select a single element.querySelectoruses CSS syntax to find the first match.querySelectorAllfinds all matches and returns a NodeList.
Quick Quiz
Which method returns a NodeList?
Enjoying these tutorials?