Codetainer LogoCodetainer Acad

Lessons

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 ID
  • document.querySelector("selector") – select the first match using CSS selector
  • document.querySelectorAll("selector") – select all matches as a static NodeList
  • document.getElementsByClassName("class") – live HTMLCollection by class name
  • document.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

  • querySelectorAll gives a static NodeList (won’t update if the DOM changes)
  • getElementsByClassName and getElementsByTagName return 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 getElementById for IDs
  • Use querySelector for first-match CSS-style selecting
  • Use querySelectorAll for 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!

CodetainerAcad