The DOM: Finding Elements
The bridge between JavaScript and your HTML. The DOM lets JS read and grab any element on the page.
What you will learn
- Understand what the DOM is
- Select elements with querySelector and getElementById
- Read element content
What is the DOM?
When the browser loads your HTML, it builds a live, in-memory tree of all the elements called the DOM (Document Object Model). JavaScript can read and change this tree — and the page updates instantly.
Selecting elements
| Method | Finds |
|---|---|
document.getElementById("x") | The element with id="x" |
document.querySelector(".card") | The FIRST match for a CSS selector |
document.querySelectorAll(".card") | ALL matches (a list) |
Let us grab a real element and read what is inside it. We have an <h1> with id="title", then JavaScript finds it and reads its text.
<h1 id="title">Original Title</h1>
<p class="info">Some info.</p>
<script>
const heading = document.getElementById("title");
document.write("The heading says: " + heading.textContent);
</script>document.getElementById("title") searches the page for the element whose id is "title" and hands it back; we store it in heading. Then heading.textContent reads the words inside that element ("Original Title"), which we print.
Note: Output:
Original Title
The heading says: Original Title
(The <h1> still shows on the page as normal; our script separately read its text and printed it below.)
Tip: querySelector uses the same selectors as CSS: "#id", ".class", "tag". If you know CSS selectors, you already know how to find elements in JavaScript.
Q. Which selects the element with id="menu"?
✍️ Practice
- Add an element with an id and use JS to read and print its text.
- Use
querySelectorAllto count how many paragraphs are on a page.
🏠 Homework
- Select three different elements (by id, by class, by tag) and log each to the console.