DOM Manipulation3/17

Selecting Elements

Finding Elements ๐Ÿ”

Before you can change an element, you need to select it!

Why Select Elements?

// Can't do this - need to select first!
<h1>.textContent = "Hello";  // โŒ

// Select, then modify
const h1 = document.querySelector("h1");
h1.textContent = "Hello";  // โœ…

Method 1: getElementById

Get ONE element by its ID:

// HTML: <div id="header">...</div>
const header = document.getElementById("header");

Method 2: querySelector (Most Popular!)

Uses CSS selectors - very flexible:

// By ID
document.querySelector("#header");

// By class
document.querySelector(".menu-item");

// By tag
document.querySelector("button");

// Complex selectors
document.querySelector("div.container > p.intro");

Method 3: querySelectorAll

Get ALL matching elements (returns NodeList):

const allButtons = document.querySelectorAll("button");
// NodeList of all buttons

allButtons.forEach(btn => {
  console.log(btn.textContent);
});

Comparison

MethodReturnsUse When
getElementByIdOne element or nullYou know the ID
querySelectorFirst match or nullNeed one element
querySelectorAllNodeList (can be empty)Need all matches

Your Turn!

Create a function that gets an element by its ID.