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
| Method | Returns | Use When |
|---|---|---|
getElementById | One element or null | You know the ID |
querySelector | First match or null | Need one element |
querySelectorAll | NodeList (can be empty) | Need all matches |
Your Turn!
Create a function that gets an element by its ID.