JavaScript Tutorial · JavaScript in the Browser · Lesson 40 of 44
JavaScript HTML DOM
The Document Object Model: how JavaScript sees and changes a web page.
What is the DOM?
When a browser loads a page, it builds the DOM (Document Object Model) — a tree of objects, one per element. JavaScript reads and changes that tree, and the browser updates the page.
document
└── html
├── head
│ └── title
└── body
├── h1
└── p
Finding elements
| Method | Returns |
|---|---|
document.getElementById("id") |
one element or null |
document.querySelector("css selector") |
the first match or null |
document.querySelectorAll("css selector") |
all matches (a NodeList) |
querySelector accepts any CSS selector — #id, .class, ul > li:first-child — so it's all you usually need.
Changing content
Press Run to see the result rendered below the example:
<h1 id="headline">Old headline</h1>
<ul>
<li class="item">One</li>
<li class="item">Two</li>
<li class="item">Three</li>
</ul>
<p id="info"></p>
<script>
document.getElementById("headline").textContent = "Updated by JavaScript";
const items = document.querySelectorAll(".item");
items.forEach((li, i) => (li.textContent = `Item #${i + 1}`));
document.querySelector("#info").textContent = `Found ${items.length} items.`;
</script>
Use textContent for plain text. innerHTML parses HTML — never put user input into it, or you open the door to XSS attacks.
Test yourself
Which method returns ALL elements matching a CSS selector?
document.querySelector()document.getElementById()document.querySelectorAll()document.find()
Show answer
Answer: document.querySelectorAll()