The DOM
While modern JavaScript is used heavily on the backend, it is impossible to discuss the language without mentioning its original and primary use case: manipulating web pages in the browser.
The DOM (Document Object Model) is the browser’s in-memory, tree-like representation of an HTML document.
When a browser loads an HTML file, it converts every single HTML tag into a JavaScript object (a “node”). Your JavaScript code can interact with these nodes via a globally available object called document.
Selecting Elements
You can ask the DOM to find specific HTML elements using their IDs, classes, or tag names.
<!-- HTML -->
<h1 id="mainHeading">Welcome!</h1>
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
// JavaScript
const heading = document.getElementById("mainHeading");
const paragraphs = document.getElementsByClassName("text");
Manipulating Elements
Once you have a reference to a DOM node in JavaScript, you can change its text, alter its CSS styles, or dynamically add new HTML inside it.
heading.textContent = "Welcome to the updated club!";
// Change the style of the first paragraph
paragraphs[0].style.color = "red";
Event Listeners
The most powerful aspect of the DOM is interactivity. You can attach “Event Listeners” to DOM nodes to trigger JavaScript functions whenever a user clicks, types, or scrolls.
<button id="joinButton">Join</button>
const button = document.getElementById("joinButton");
// When the user clicks the button, execute this function
button.addEventListener("click", () => {
console.log("Button was clicked!");
});