Lesson 21: Selecting Elements in the DOM
π Lesson 21: Selecting Elements in the DOM
Before we can change, move, hide, or animate anything on a webpage with JavaScript, we need to grab the HTML elements we want to work with. This is called DOM selection.
π What is the DOM?
The DOM (Document Object Model) is a tree-like structure of your webpage. Every tag (like <p>, <div>, etc) becomes a node that JavaScript can interact with.
π― DOM Selection Methods
Here are the most common ways to select elements:
document.getElementById("id")β select one element by IDdocument.querySelector("selector")β select the first match using CSS selectordocument.querySelectorAll("selector")β select all matches as a static NodeListdocument.getElementsByClassName("class")β live HTMLCollection by class namedocument.getElementsByTagName("tag")β live HTMLCollection by tag
π§ͺ Example
// Select by ID
const title = document.getElementById("main-title");
// Select first <p> using CSS selector
const firstParagraph = document.querySelector("p");
// Select all <p> tags (static NodeList)
const allParagraphs = document.querySelectorAll("p");
// Select by class name (live HTMLCollection)
const redBoxes = document.getElementsByClassName("red-box");
// Select by tag name (live HTMLCollection)
const allDivs = document.getElementsByTagName("div");
π Static vs Live Collections
querySelectorAllgives a static NodeList (wonβt update if the DOM changes)getElementsByClassNameandgetElementsByTagNamereturn live collections (auto-update when the DOM changes)
βοΈ Real Use Case
Letβs say you want to hide all paragraphs on a page:
const allParagraphs = document.querySelectorAll("p");
allParagraphs.forEach(p => {
p.style.display = "none";
});
π§ Summary
- Use
getElementByIdfor IDs - Use
querySelectorfor first-match CSS-style selecting - Use
querySelectorAllfor multiple matches - Live collections update automatically; static ones donβt
- Everything starts with selecting the right element
In the next lesson, weβll make DOM elements change, move, and react using JavaScript. Buckle up!