The DOM & EventsCore· 40 min read

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

MethodFinds
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.

Grab an element and read 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>
Live preview

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"?

Answer: getElementById("menu") (or querySelector("#menu")) selects the element whose id is menu.

✍️ Practice

  1. Add an element with an id and use JS to read and print its text.
  2. Use querySelectorAll to count how many paragraphs are on a page.

🏠 Homework

  1. Select three different elements (by id, by class, by tag) and log each to the console.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →