JavaScript DOM Introduction: Nodes, Elements and document
Learn what the DOM is, how the browser turns HTML into a tree of nodes, and how the document object lets JavaScript read and change a web page.
What you will learn
So far your JavaScript has lived inside the Console. It printed numbers, played with arrays and returned values. Now it is time to do the thing JavaScript was made for: changing a real web page.
To do that, you need to understand the DOM. In this lesson you will learn what the DOM is, how the browser builds it from your HTML, what nodes and elements are, and how to use the document object as your entry point to the whole page.
What is the DOM?
DOM stands for Document Object Model. Let us break that name into three simple parts:
- Document: your web page.
- Object: every part of the page becomes a JavaScript object.
- Model: a structure that shows how those objects are connected.
Here is the idea in one picture. Think of a restaurant:
- Your HTML file is like the printed menu. It is just text.
- The DOM is like the real table with real food that the kitchen made from the menu.
- JavaScript is like a waiter who can add a dish, remove a dish or change a dish while the guest is sitting there.
When a browser loads your HTML file, it reads the text, builds the DOM, and then draws the page from the DOM. When JavaScript changes the DOM, the browser updates what you see instantly. You do not need to reload the page.
Good to know: The DOM is not part of the JavaScript language itself. It is a set of tools (an API) that the browser gives to JavaScript. That is why
documentworks in Chrome but givesReferenceError: document is not definedif you run the same code in plain Node.js.
Real-life examples of DOM changes
Every time a page changes without reloading, JavaScript is working with the DOM:
- A red badge on a shopping cart goes from
2to3. - A “Password is too short” message appears under a form field.
- A dark mode button changes the colours of the whole site.
- New posts appear as you scroll down social media.
- A popup opens and closes.
From HTML to the DOM tree
The browser does not keep your HTML as flat text. It turns it into a tree, because HTML tags sit inside other tags, just like folders sit inside other folders.
Look at this small page:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello</h1>
<p>Welcome to <b>MyCodeNest</b></p>
</body>
</html>
The browser builds this DOM tree from it:
document
└── html
├── head
│ └── title
│ └── "My Page"
└── body
├── h1
│ └── "Hello"
└── p
├── "Welcome to "
└── b
└── "MyCodeNest"
Every box in this tree is called a node. The tree uses family words:
| Word | Meaning | Example from the tree |
|---|---|---|
| Root | The very top of the tree | document |
| Parent | The node directly above | body is the parent of h1 |
| Child | A node directly below | h1 and p are children of body |
| Sibling | Nodes that share the same parent | head and body are siblings |
| Ancestor | Any node above, at any distance | html is an ancestor of b |
| Descendant | Any node below, at any distance | b is a descendant of html |
You will use these words again and again. The lesson on DOM traversal is all about moving around this family tree.
The DOM is not the same as your HTML file
This surprises many beginners. The DOM and the HTML source can be different.
- The browser fixes mistakes. If you forget
<tbody>inside a<table>, the browser adds it to the DOM for you. If you forget</p>, it closes the paragraph itself. - JavaScript changes the DOM, not the file. If your script changes the heading, the
.htmlfile on your computer stays exactly the same. Only the live DOM changes.
Tip: Right-click a page and choose Inspect. The Elements panel shows the DOM (the live version). View Page Source shows your original HTML. If JavaScript has changed the page, the two will not match.
Types of nodes
A node is the general word for “any piece of the tree”. There are several kinds. Each kind has a number called nodeType.
| Node kind | nodeType |
What it is | Example |
|---|---|---|---|
| Element | 1 |
An HTML tag | <h1>, <p>, <button> |
| Text | 3 |
The text inside a tag | "Hello" |
| Comment | 8 |
An HTML comment | <!-- note --> |
| Document | 9 |
The whole page (the root) | document |
The three properties below work on every node:
| Property | What it gives you | Example result |
|---|---|---|
nodeType |
The number from the table above | 1 |
nodeName |
The name of the node | "H1" (tags are in capital letters) |
nodeValue |
The text of a text or comment node (null for elements) |
"Hello" |
Let us check them on the practice page. This is the page used by every Try it button in this lesson:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Practice</title>
</head>
<body>
<h1 id="title">Welcome to MyCodeNest</h1>
<p class="intro">The DOM turns this page into objects.</p>
<ul id="topics">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
<p>Cart items: <span id="cart-count">0</span></p>
<button id="add-btn">Add to cart</button>
<p id="status">Loading...</p>
</body>
</html>
console.log(document.nodeType); // 9
console.log(document.documentElement.nodeName); // "HTML"
const title = document.getElementById("title");
console.log(title.nodeType); // 1 (element)
console.log(title.nodeName); // "H1"
console.log(title.nodeValue); // null (elements have no nodeValue)
console.log(title.firstChild.nodeType); // 3 (text node)
console.log(title.firstChild.nodeValue); // "Welcome to MyCodeNest"
Notice something important: the heading <h1> is one node, and the words inside it are another node (a text node, and a child of the h1). Text is never “inside” the tag in the DOM. It is a separate child.
Nodes vs elements
This is one of the most common confusions, so keep it clear:
- A node is anything in the tree: elements, text, comments, the document.
- An element is only the HTML tags. Every element is a node, but not every node is an element.
Node (anything in the tree)
├── Element <h1>, <p>, <div> ...
├── Text "Hello"
├── Comment <!-- note -->
└── Document the whole page
In your daily work you will mostly care about elements, because they are what you see and click.
Careful: Line breaks and spaces between your tags also become text nodes. That is why some properties give surprising results. You will see this clearly in the traversal lesson.
The document object
document is a ready-made object that the browser gives you. It represents the whole page and it is the starting point for everything you do with the DOM. You never create it. It is simply there.
console.log(document.title); // "DOM Practice"
console.log(document.documentElement.tagName); // "HTML"
console.log(document.head.tagName); // "HEAD"
console.log(document.body.tagName); // "BODY"
The most useful document properties:
| Property | What it gives you |
|---|---|
document.documentElement |
The <html> element |
document.head |
The <head> element |
document.body |
The <body> element |
document.title |
The text of the page title (you can read and change it) |
document.forms |
A list of all <form> elements |
document.images |
A list of all <img> elements |
document.links |
A list of all links with an href |
And the most useful document methods (you will learn them in the next lessons):
| Method | What it does |
|---|---|
document.getElementById() |
Finds one element by its id |
document.querySelector() |
Finds the first element that matches a CSS selector |
document.querySelectorAll() |
Finds all elements that match a CSS selector |
document.createElement() |
Makes a brand new element |
window vs document
Beginners often mix these two up:
window |
document |
|
|---|---|---|
| Means | The browser tab (the whole environment) | The web page inside the tab |
| Contains | alert(), setTimeout(), localStorage, location |
body, title, getElementById() |
| Relationship | document is a property of window |
window.document is the same as document |
You can write window.document or just document. Everyone writes document.
Your first DOM changes
Enough theory. Let us change the page. We will use getElementById, textContent and style. Do not worry about the details yet, because the next lessons explain them one by one.
const title = document.getElementById("title");
title.textContent = "Hello, DOM!"; // change the text
title.style.color = "tomato"; // change the colour
Click Try it, and watch the heading change on the preview. You just changed a live web page with two lines of code.
Real use case: a cart counter
Online shops update the little number on the cart icon every time you add a product. Here is the idea. The page has a <span id="cart-count">0</span> and a button. When the button is clicked, we add one to the number.
const badge = document.getElementById("cart-count");
const button = document.getElementById("add-btn");
button.addEventListener("click", function () {
const current = Number(badge.textContent); // read: "0" becomes 0
badge.textContent = current + 1; // write: show the new number
});
Click Try it, then press the Add to cart button in the preview. The number goes up each time.
Note:
addEventListenermeans “when this happens, run this function”. It belongs to the events topic, which you will study in detail later. For now, read it as: “when the button is clicked, do this.” The important part is the pattern: find the element → read it → change it.
Real use case: greet the visitor
Websites often say “Good morning” or “Good evening”. The idea: ask the computer for the current hour, pick a message, and write it into the page.
const status = document.getElementById("status");
const hour = new Date().getHours();
let greeting = "Good evening";
if (hour < 12) {
greeting = "Good morning";
} else if (hour < 18) {
greeting = "Good afternoon";
}
status.textContent = greeting + "! Welcome back.";
Adding something new to the page
The DOM is live. You can also create brand new elements and put them in the tree:
const list = document.getElementById("topics");
console.log(list.children.length); // 3
const li = document.createElement("li"); // 1. make a new <li>
li.textContent = "React"; // 2. give it text
list.append(li); // 3. put it in the list
console.log(list.children.length); // 4
Three steps: create, fill, attach. A new element does not appear on the page until you attach it to the tree.
CSS and JavaScript share the same DOM
CSS and JavaScript do not talk to your HTML file. They both talk to the DOM.
- CSS looks at the DOM tree, finds elements with selectors, and decides how they look.
- JavaScript looks at the same tree, finds elements, and decides what they do and say.
That is why a selector like .intro works in both places:
.intro {
color: seagreen;
font-size: 1.2rem;
}
const intro = document.querySelector(".intro");
intro.style.fontWeight = "bold";
CSS styles .intro using the selector. JavaScript finds the very same element using the very same selector. This is why learning CSS selectors first makes selecting elements in JavaScript much easier. If you need a refresher, read CSS Selectors in Depth.
When does your script run?
Your script can only find an element after the browser has built it. If your script runs too early, the element does not exist yet and you get null.
<!-- Wrong: the script runs before the <h1> exists -->
<head>
<script>
const title = document.getElementById("title");
console.log(title); // null
</script>
</head>
<body>
<h1 id="title">Hello</h1>
</body>
There are two easy fixes. Choose either one:
<!-- Fix 1: put the script at the end of the body -->
<body>
<h1 id="title">Hello</h1>
<script src="script.js"></script>
</body>
<!-- Fix 2: keep it in the head, but add defer -->
<head>
<script src="script.js" defer></script>
</head>
<body>
<h1 id="title">Hello</h1>
</body>
defer tells the browser: “Download the script now, but run it only after the whole HTML is read.” Modern projects mostly use defer.
Tip: The MyCodeNest code editor puts your
script.jsat the end of the body for you, so the examples in these lessons just work.
Common mistakes
- Running the script before the element exists. You get
null, and thenCannot read properties of null. Put the script at the end of<body>or usedefer. - Thinking the DOM is the HTML file. The browser fixes mistakes and JavaScript changes the DOM. The file does not change. Use Inspect to see the live DOM.
- Mixing up nodes and elements. A text node is a node but not an element. Only tags are elements.
- Using
#ingetElementById. WritegetElementById("title"), notgetElementById("#title"). The#is only for CSS selectors. - Expecting to see an element when you
console.logit in this editor. Log something readable instead, liketitle.textContentortitle.tagName. - Using
documentin Node.js.documentbelongs to the browser. In Node.js you getReferenceError. - Forgetting to attach a new element.
document.createElement("li")only makes it. It will not show up until you useappend()on a parent.
Practice
-
Click Practice in Editor. Use
document.titleto print the page title in the console. -
Change the heading text to your own name.
-
Print
nodeTypeandnodeNamefor the<ul id="topics">element. Is it a node? Is it an element? -
Print the
nodeValueof the first child of the heading. Why is it notnull? -
Change the colour of the heading to any colour you like using
style.color. -
Add two new items,
Node.jsandMongoDB, to the topics list. Print the final number of items. -
Change the page title with
document.title = "My New Title". Look at the browser tab (open the editor preview in its own tab if you can). -
Make the cart button add 2 to the counter each time, instead of 1.
-
Update the
statusparagraph to show today’s date. Hint:new Date().toDateString(). -
Challenge: draw the DOM tree for this HTML on paper, with parent and child nodes:
<div> <h2>Title</h2> <p>Hello <em>world</em></p> </div>
Recap
- The DOM is a live, tree-shaped model of your page made of JavaScript objects. The browser builds it from your HTML.
- JavaScript changes the DOM, not your HTML file, and the page updates instantly.
- The DOM belongs to the browser, not to the JavaScript language.
- Everything in the tree is a node. Elements are one kind of node. Text and comments are other kinds.
- Common
nodeTypevalues:1element,3text,8comment,9document. documentis your starting point. It gives youbody,head,titleand methods likegetElementById.- The pattern of DOM work is: find → read or change. Create new elements with
createElement, then attach them withappend. - Run your script after the HTML exists: end of
<body>, ordefer. - Next you will learn the five ways to find elements on the page:
getElementById,getElementsByClassName,getElementsByTagName,querySelectorandquerySelectorAll.