Working with the DOM
Prerequisites: Functions
The DOM (Document Object Model) is the browser's live, in-memory representation of a web page — JavaScript can read and change it, which is what makes pages interactive.
const heading = document.querySelector("h1");
heading.textContent = "Updated by JavaScript!";
heading.style.color = "blue";
const button = document.createElement("button");
button.textContent = "Click me";
document.body.appendChild(button);
document.querySelector(selector) finds the first element matching a
CSS selector; querySelectorAll finds all of them.
Common mistakes
- Running DOM-manipulating code before the page has finished loading —
querySelectorreturnsnullfor an element that doesn't exist yet. Place<script>tags at the end of<body>, or wrap code in aDOMContentLoadedevent listener.