DOM Intro
The DOM (Document Object Model) is the browser's in-memory representation of an HTML page. JavaScript can read it, change it, and react to user actions on it.
Finding elements
| Method | Returns |
|---|---|
document.getElementById("hero") | Single element or null. |
document.querySelector(".btn") | First match (any CSS selector). |
document.querySelectorAll("li") | NodeList of all matches. |
document.getElementsByClassName(…) | Live HTMLCollection. |
Reading & changing
JS
const title = document.querySelector("h1");
title.textContent = "Updated!"; // safe: text only
title.innerHTML = "<em>ok</em>"; // parses HTML — only with trusted content
title.classList.add("active");
title.classList.toggle("dark");
title.style.color = "#04AA6D";
title.setAttribute("data-status", "ready");
title.dataset.status = "ready"; // same thing via dataset shorthand
Creating & inserting
JS
const li = document.createElement("li");
li.textContent = "New item";
document.querySelector("ul").appendChild(li);
// Or the one-liner
document.querySelector("ul").insertAdjacentHTML("beforeend", "<li>New item</li>");
Reacting to events
JS
document.querySelector("#btn").addEventListener("click", (e) => {
console.log("clicked", e.target);
});
// Event delegation — listen on the parent for clicks on dynamic children
document.querySelector("ul").addEventListener("click", (e) => {
if (e.target.matches("li")) console.log("item:", e.target.textContent);
});
Security: Always prefer
textContent over innerHTML for user-supplied data. Setting innerHTML with user input is the classic XSS hole.Example
Example
<!DOCTYPE html>
<html>
<body>
<button onclick="paint()">Click me</button>
<p id="out">Waiting...</p>
<script>
function paint() {
const el = document.getElementById("out");
el.textContent = "Clicked at " + new Date().toLocaleTimeString();
el.style.color = "#04AA6D";
}
</script>
</body>
</html>
Try it Yourself »
Exercise
Find the first element matching the .btn class.
const btn = document.
('.btn');
Modern method that accepts any CSS selector.
Discussion
Loading…