Now that you understand the DOM as a tree structure, let's learn how to grab specific elements from it!
JavaScript needs a way to find and select an element before it can change it. Think of it like finding a specific book in a library.
Engagement Message
What must JavaScript do first before it can change something on a webpage?
The most common way to select an element is using getElementById
. This method finds an element by its unique id
attribute.
Remember how HTML elements can have an id="something"
? That's exactly what this method looks for!
Engagement Message
If you had <p id="intro">Hello</p>
, what is the element's ID?
Here's how getElementById
works in JavaScript:
document.getElementById("intro");
This code tells JavaScript: "Go find the element with the ID 'intro' in the document
." The word document
represents your entire HTML page.
Engagement Message
What goes inside the parentheses and quotes?
Another powerful method is querySelector
. This is more flexible—it can find elements by ID, class, or tag name, using CSS selector syntax.
