JavaScript and the DOM: A Beginner-Friendly Introduction
This article is a complementary resource to the JavaScript in Browser course.
This article is a complementary resource to the JavaScript in Browser course.
At their cores, webpages are HTML documents; it's the browser that converts this document into the interactive wonders you see on your screen.
How does the browser do this?
Well, your browser organizes the page into a structured tree-like representation known as the Document Object Model (DOM).
In simple terms, the DOM is how your browser sees and understands your webpage.
In this article, you'll learn the basics of how the DOM works.
The name Document Object Model might sound technical, but when you break it down, it actually makes perfect sense. Let's break down the terms in DOM individually:
Document: This represents your entire webpage (the HTML document) that the browser loads and displays.
Object: Instead of treating the webpage as just a long block of text, the browser organizes it into structured objects that JavaScript can interact with.
Model:
Every element (like
<div>
,
<h1>
, or
<button>
) is part of a hierarchy, making it easy to find, update, and manipulate specific parts of the page dynamically.
Basically, the DOM:
Let's say you have this simple HTML:
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
<button onclick="changeText()">Click Me</button>
</body>
</html>
When your browser loads this page, it creates a DOM tree like this:
As you can see, the DOM has converted our HTML to a hierarchical tree structure:
<html>
tag is a child of the
document.<head>
and
<body>
tags are the children of
<html>
.<title>
,
<h1>
,
<p>
, and
<button>
tags.This structure makes it easy for JavaScript to find and modify specific elements.
Now that we understand the structure of the DOM, let's see how JavaScript can modify it in real-time!
Let's write some JavaScript to change the text of our
<h1>
tag when the button is clicked.
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
<button onclick="changeText()">Click Me</button>
</body>
<script>
function changeText() {
// Select the <h1> element
const header = document.querySelector("h1")
// Change the text of <h1>
header.innerText = "You clicked the button!";
}
</script>
</html>
1. The button triggers the
changeText()
function when clicked.
2. JavaScript searches through the DOM and selects the
<h1>
element using
querySelector()
.
3. It then modifies the text such that you can see the change instantly (without requiring to refresh your page).
This is just a simple example, but the same concept powers modern web apps like:
By mastering the DOM, you can build dynamic, fast, and interactive websites just like the pros!