To manipulate an HTML element, you must first find it. In JavaScript, there are several ways to select elements from the DOM tree, ranging from simple ID searches to complex CSS selections.
The most common and fastest way to find an HTML element in the DOM is using the element id. If the element is found, the method will return it as an object.
const element = document.getElementById("intro");
Finding elements by their tag name returns an HTMLCollection of matching elements.
const items = document.getElementsByTagName("li");
If you want to find all HTML elements with a specific class name, use
getElementsByClassName().
const x = document.getElementsByClassName("intro");
If you want to find HTML elements that match a specified CSS selector (id,
class names, types, attributes, etc.), use the querySelectorAll() method.
const x = document.querySelectorAll("p.intro");
The document object has built-in collections for certain types of elements,
like forms.
const form = document.forms["myForm"];
getElementsBy... methods return a
Live HTMLCollection, while querySelectorAll() returns a
Static NodeList. This means the NodeList won't update automatically if you add new elements later!
querySelector() returns only the first
matchquerySelectorAll() returns every match as a NodeListfor loop or
forEach() (on NodeLists)document object must exist before calling these
methods