DOM Fundamentals
By Syncfusion®, Inc. · Last updated
What the DOM is, DOM methods and properties, finding elements by id, class, tag and selector, and creating, adding, replacing, removing and deleting elements through the document object.
What Is the DOM?
DOM (Document Object Model) = the browser's version of your page as a tree of objects.
- Every HTML tag becomes an object JavaScript can find, read and change.
- Change the object, and the page updates at once.
- Method = does work (
append()); property = holds a value (id).
Simple lesson: find an element, then change it. That is all DOM code is.
A Real-World Example
A new order arrives on a shop's admin page.
JavaScript finds the order list with document.getElementById("orders"), makes a new <li>, and adds it.
The row appears instantly, with no page reload.
html
body
ul#orders
li 1001 li 1002 new li 1003
The page is a tree. Adding an object adds a row on screen.
Each box in this lesson is a small live page: HTML markup plus a <script>. The page shows beside the code, and console.log prints below. One box fails on purpose.
What You Will Learn
- What the DOM is, and methods versus properties.
- Finding elements by id, class, tag and CSS selector.
- Creating, adding, replacing and removing elements.
- The
documentobject. - Each key method, what it returns, and its traps.
DOM manipulation
DOM manipulation = changing a page with JavaScript after it loads: add a row, remove a done task, update a total.
The browser turns markup into objects that JavaScript can read
<h1>Today's orders</h1>
<ul id="orders">
<li>Order 1001 for Asha</li>
<li>Order 1002 for Ravi</li>
</ul>
<script>
const list = document.getElementById("orders");
console.log("tag name:", list.tagName);
console.log("number of items:", list.children.length);
console.log("first item:", list.children[0].textContent);
</script>
Expected output:
tag name: UL
number of items: 2
first item: Order 1001 for Asha
Why "tree"? Each element sits inside another: the <ul> is a branch; each <li> is a leaf on it.
DOM methods and properties
- Method: call it with brackets, like
list.append(item). - Property: read it without brackets, like
list.id.
Properties hold values, and methods do work
<ul id="orders">
<li>Order 1001 for Asha</li>
</ul>
<script>
const list = document.getElementById("orders");
// Properties: values you read.
console.log("id property:", list.id);
console.log("tagName property:", list.tagName);
// A method: a function you call.
const item = document.createElement("li");
item.textContent = "Order 1002 for Ravi";
list.append(item);
console.log("items after calling append():", list.children.length);
</script>
Expected output:
id property: orders
tagName property: UL
items after calling append(): 2
Accessing HTML elements
Store the element in a variable: a reference. Two searches for the same element give the same object.
Two searches for the same element return the same object
<p id="status">Waiting for orders</p>
<script>
const first = document.getElementById("status");
const second = document.getElementById("status");
console.log("same object?", first === second);
first.textContent = "3 new orders";
console.log("read through the other variable:", second.textContent);
</script>
Expected output:
same object? true
read through the other variable: 3 new orders
A script can only find elements that already exist. Put your script at the end of <body>, or add defer to the <script> tag. These boxes always run the script after the markup.
Finding elements
Search by id, class, tag, or any CSS selector (#id, .class, li). Some return one element, some a group.
Five ways to search the same small page
<ul id="orders">
<li class="order urgent">Order 1001 for Asha</li>
<li class="order">Order 1002 for Ravi</li>
<li class="order urgent">Order 1003 for Meera</li>
</ul>
<script>
console.log("by id:", document.getElementById("orders").id);
console.log("by class:", document.getElementsByClassName("urgent").length);
console.log("by tag:", document.getElementsByTagName("li").length);
console.log("first match of a selector:", document.querySelector(".urgent").textContent);
console.log("every match of a selector:", document.querySelectorAll(".order").length);
</script>
Expected output:
by id: orders
by class: 2
by tag: 3
first match of a selector: Order 1001 for Asha
every match of a selector: 3
Creating elements
document.createElement("li") builds an element in memory. It is not on the page until you add it. isConnected tells you.
A new element exists before it is on the page
<ul id="orders"></ul>
<script>
const item = document.createElement("li");
item.textContent = "Order 1004 for Kiran";
console.log("on the page before adding?", item.isConnected);
document.getElementById("orders").append(item);
console.log("on the page after adding?", item.isConnected);
</script>
Expected output:
on the page before adding? false
on the page after adding? true
Modifying elements
Change textContent, id or className, and the page updates at once. A search for the old id now finds null.
Changing the text, the id and the class of one element
<p id="banner" class="notice">Shop opens at 9</p>
<script>
const banner = document.getElementById("banner");
banner.textContent = "Shop is open now";
banner.className = "notice open";
banner.id = "open-banner";
console.log("text:", banner.textContent);
console.log("class:", banner.className);
console.log("found by the old id?", document.getElementById("banner"));
console.log("found by the new id?", document.getElementById("open-banner") === banner);
</script>
Expected output:
text: Shop is open now
class: notice open
found by the old id? null
found by the new id? true
Removing elements
element.remove() takes it off the page. The variable still holds it.
A removed element leaves the page but still exists in the variable
<ul id="tasks">
<li id="pack">Pack order 1001</li>
<li id="ship">Ship order 1001</li>
</ul>
<script>
const pack = document.getElementById("pack");
pack.remove();
console.log("items left:", document.getElementById("tasks").children.length);
console.log("still in the variable:", pack.textContent);
console.log("on the page?", pack.isConnected);
</script>
Expected output:
items left: 1
still in the variable: Pack order 1001
on the page? false
Adding new HTML elements
parent.append(child): inside, at the end.parent.prepend(child): inside, at the start.element.before(other): right before it, as a neighbour.element.after(other): right after it, as a neighbour.
append, prepend, before and after place an element in four different spots
<ul id="queue">
<li id="ravi">Ravi</li>
</ul>
<script>
const queue = document.getElementById("queue");
const ravi = document.getElementById("ravi");
function person(name) {
const item = document.createElement("li");
item.textContent = name;
return item;
}
queue.append(person("Meera (append)"));
queue.prepend(person("Asha (prepend)"));
ravi.before(person("Kiran (before Ravi)"));
ravi.after(person("Divya (after Ravi)"));
for (const item of queue.children) {
console.log(item.textContent);
}
</script>
Expected output:
Asha (prepend)
Kiran (before Ravi)
Ravi
Divya (after Ravi)
Meera (append)
An element is in one place at a time. Appending an element already on the page moves it. For a copy, use element.cloneNode(true).
Replacing HTML elements
old.replaceWith(newOne) swaps them in the same spot; nothing else moves.
replaceWith swaps an old element for a new one in the same position
<ul id="orders">
<li>Order 1001, packed</li>
<li id="pending">Order 1002, pending</li>
<li>Order 1003, packed</li>
</ul>
<script>
const pending = document.getElementById("pending");
const shipped = document.createElement("li");
shipped.textContent = "Order 1002, shipped";
pending.replaceWith(shipped);
for (const item of document.getElementById("orders").children) {
console.log(item.textContent);
}
</script>
Expected output:
Order 1001, packed
Order 1002, shipped
Order 1003, packed
Deleting HTML elements
Delete with remove() and drop the reference. parent.replaceChildren() with nothing inside empties a container.
Delete every finished task, then empty the whole list
<ul id="tasks">
<li class="done">Pack order 1001</li>
<li>Ship order 1001</li>
<li class="done">Email Asha</li>
</ul>
<script>
const tasks = document.getElementById("tasks");
document.querySelectorAll(".done").forEach((task) => task.remove());
console.log("after deleting finished tasks:", tasks.children.length, "left");
console.log("the one left:", tasks.children[0].textContent);
tasks.replaceChildren();
console.log("after emptying the list:", tasks.children.length, "left");
</script>
Expected output:
after deleting finished tasks: 1 left
the one left: Ship order 1001
after emptying the list: 0 left
DOM manipulation using the document object
document is the starting point: documentElement (<html>), head, body and title.
The document object leads to the main parts of the page
<h1>Order board</h1>
<script>
console.log("the root element:", document.documentElement.tagName);
console.log("the head:", document.head.tagName);
console.log("the body:", document.body.tagName);
console.log("first thing in the body:", document.body.firstElementChild.textContent);
document.title = "Order board";
console.log("page title:", document.title);
</script>
Expected output:
the root element: HTML
the head: HEAD
the body: BODY
first thing in the body: Order board
page title: Order board
Key methods
getElementById()
Finds the one element with that id. Pass the bare id, with no #.
getElementById takes the bare id, with no # in front
<p id="total">Total: 3 orders</p>
<script>
console.log("with the bare id:", document.getElementById("total").textContent);
console.log("with a # in front:", document.getElementById("#total"));
</script>
Expected output:
with the bare id: Total: 3 orders
with a # in front: null
getElementsByClassName()
Every element with a class, as an HTMLCollection. It is live: it updates itself when the page changes. It has no forEach.
A live collection grows by itself when a matching element is added
<ul id="orders">
<li class="urgent">Order 1001 for Asha</li>
</ul>
<script>
const urgent = document.getElementsByClassName("urgent");
console.log("urgent orders before:", urgent.length);
const item = document.createElement("li");
item.className = "urgent";
item.textContent = "Order 1005 for Ravi";
document.getElementById("orders").append(item);
console.log("urgent orders after:", urgent.length);
console.log("has forEach?", typeof urgent.forEach);
</script>
Expected output:
urgent orders before: 1
urgent orders after: 2
has forEach? undefined
Why "live"? It stays connected to the page, not a one-time snapshot.
getElementsByTagName()
Every element with a tag name, also live. Call it on document, or on one element to search only inside it.
Searching the whole page, then searching inside one list
<ul id="today">
<li>Order 1001</li>
<li>Order 1002</li>
</ul>
<ul id="tomorrow">
<li>Order 1003</li>
</ul>
<script>
console.log("li on the whole page:", document.getElementsByTagName("li").length);
const tomorrow = document.getElementById("tomorrow");
console.log("li inside #tomorrow:", tomorrow.getElementsByTagName("li").length);
</script>
Expected output:
li on the whole page: 3
li inside #tomorrow: 1
querySelector()
The first match for any CSS selector, or null.
querySelector accepts any CSS selector and returns the first match
<ul id="orders">
<li class="order">Order 1001 for Asha</li>
<li class="order paid">Order 1002 for Ravi</li>
<li class="order paid" data-id="1003">Order 1003 for Meera</li>
</ul>
<script>
console.log("by id:", document.querySelector("#orders").id);
console.log("first .order:", document.querySelector(".order").textContent);
console.log("first .paid:", document.querySelector(".paid").textContent);
console.log("by attribute:", document.querySelector("[data-id='1003']").textContent);
console.log("no match:", document.querySelector(".cancelled"));
</script>
Expected output:
by id: orders
first .order: Order 1001 for Asha
first .paid: Order 1002 for Ravi
by attribute: Order 1003 for Meera
no match: null
Using that null throws:
Using the null from a failed search throws an error
<p id="total">Total: 3 orders</p>
<script>
// "totl" is a typo, so nothing matches and querySelector returns null.
document.querySelector("#totl").textContent = "Total: 4 orders";
</script>
Cannot read/set properties of null in DOM code usually means a search found nothing: a typo, a missing # or ., or a script that ran too early. Guard with if (element) or element?.remove().
querySelectorAll()
Every match, as a NodeList. It is static (a snapshot). It has forEach, but not map; use [...list] or Array.from(list) for array methods.
A NodeList is a snapshot, and it has forEach but not map
<ul id="orders">
<li class="paid">Order 1001 for Asha</li>
<li class="paid">Order 1002 for Ravi</li>
</ul>
<script>
const paid = document.querySelectorAll(".paid");
console.log("paid orders:", paid.length);
const item = document.createElement("li");
item.className = "paid";
item.textContent = "Order 1003 for Meera";
document.getElementById("orders").append(item);
console.log("after adding one, the snapshot still says:", paid.length);
paid.forEach((order) => console.log("forEach:", order.textContent));
console.log("has map?", typeof paid.map);
const names = [...paid].map((order) => order.textContent.split(" for ")[1]);
console.log("after spreading into an array:", names.join(", "));
</script>
Expected output:
paid orders: 2
after adding one, the snapshot still says: 2
forEach: Order 1001 for Asha
forEach: Order 1002 for Ravi
has map? undefined
after spreading into an array: Asha, Ravi
createElement()
The usual pattern: create, fill, add. One element per item of data.
Building one list item for each order in an array
<ul id="orders"></ul>
<script>
const orders = [
{ id: 1001, customer: "Asha", total: 450 },
{ id: 1002, customer: "Ravi", total: 1200 },
{ id: 1003, customer: "Meera", total: 300 },
];
const list = document.getElementById("orders");
for (const order of orders) {
const item = document.createElement("li");
item.className = "order";
item.textContent = `Order ${order.id} for ${order.customer}: ₹${order.total}`;
list.append(item);
}
console.log("items built:", list.children.length);
console.log("last item:", list.lastElementChild.textContent);
</script>
Expected output:
items built: 3
last item: Order 1003 for Meera: ₹300
appendChild()
The older append(): one node only, and it returns that node. A plain string throws; append() accepts text.
appendChild takes one node and returns it, while append also accepts text
<ul id="orders"></ul>
<script>
const list = document.getElementById("orders");
const item = document.createElement("li");
item.textContent = "Order 1001 for Asha";
const returned = list.appendChild(item);
console.log("returns the same node?", returned === item);
try {
list.appendChild("Order 1002 for Ravi");
} catch (error) {
console.log("appendChild with plain text:", error.name);
}
const second = document.createElement("li");
second.append("Order 1002 for Ravi");
list.append(second);
console.log("append accepts text:", second.textContent);
</script>
Expected output:
returns the same node? true
appendChild with plain text: TypeError
append accepts text: Order 1002 for Ravi
prepend()
Adds before the first child: newest-first lists.
prepend puts the newest order at the top of the list
<ul id="feed">
<li>Order 1001 for Asha</li>
</ul>
<script>
const feed = document.getElementById("feed");
for (const text of ["Order 1002 for Ravi", "Order 1003 for Meera"]) {
const item = document.createElement("li");
item.textContent = text;
feed.prepend(item);
}
for (const item of feed.children) {
console.log(item.textContent);
}
</script>
Expected output:
Order 1003 for Meera
Order 1002 for Ravi
Order 1001 for Asha
replaceChild()
The older replace, called on the parent, with the new child first: parent.replaceChild(newItem, oldItem).
replaceChild is called on the parent, with the new child first
<ul id="orders">
<li id="old">Order 1002, pending</li>
</ul>
<script>
const list = document.getElementById("orders");
const oldItem = document.getElementById("old");
const newItem = document.createElement("li");
newItem.textContent = "Order 1002, shipped";
const removed = list.replaceChild(newItem, oldItem);
console.log("now in the list:", list.children[0].textContent);
console.log("returned:", removed.textContent);
</script>
Expected output:
now in the list: Order 1002, shipped
returned: Order 1002, pending
remove()
The method to use for removing. Trap: removing by index from a live collection skips items, because the list shrinks under you.
Removing from a live collection by index skips every other item
<ul id="tasks">
<li class="done">Pack order 1001</li>
<li class="done">Pack order 1002</li>
<li class="done">Pack order 1003</li>
</ul>
<script>
const done = document.getElementsByClassName("done");
for (let i = 0; i < done.length; i++) {
done[i].remove();
}
console.log("finished tasks still on the page:", done.length);
console.log("the one that was skipped:", done[0].textContent);
</script>
Expected output:
finished tasks still on the page: 1
the one that was skipped: Pack order 1002
getElementById()/querySelector() → one element or null. getElementsBy...() → live HTMLCollection. querySelectorAll() → static NodeList.
The DOM in the Editor
The same ideas in the live editor: find the list, create one <li> per order, and remove one with a button.
Building an order board from data
const orders = [
{ id: 1001, customer: "Asha", total: 349 },
{ id: 1002, customer: "Ravi", total: 120 },
{ id: 1003, customer: "Meera", total: 599 },
];
const list = document.getElementById("orders");
for (const order of orders) {
const li = document.createElement("li");
li.textContent = `#${order.id} ${order.customer} — ₹${order.total} `;
const done = document.createElement("button");
done.textContent = "Done";
done.addEventListener("click", () => {
li.remove();
console.log("removed", order.id, "| left:", list.children.length);
});
li.append(done);
list.append(li);
}
const heading = document.querySelector("h2");
heading.textContent = `Today's orders (${list.children.length})`;
Easy way to remember: find → change. querySelector finds one, querySelectorAll finds all, createElement + append adds.
TL;DR
- The DOM is the page as a tree of objects.
- Find with
getElementById,querySelectorandquerySelectorAll. - Create with
createElement; add withappend,prepend,before,after. - Replace with
replaceWith; remove withremove(). - Live collections update themselves;
NodeListsnapshots do not.
Try this
In the querySelectorAll() box, switch to document.getElementsByClassName("paid") and delete the forEach lines. The "after adding one" line now says 3: a live collection updates itself.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Using a search result without checking | Searches always find | They can return null | Cannot set properties of null |
getElementById("#total") | It takes a selector | It takes the bare id | null |
list.map(...) on a search result | Results are arrays | Use [...list] | map is not a function |
createElement without adding | It appears by itself | Add it with append() | Nothing shows |
| Removing by index from a live collection | The list stays still | It shrinks | Items are skipped |
A script in <head> | Elements already exist | Put it at the end, or defer | Every search is null |
Quick reference
| Syntax | Meaning |
|---|---|
document.getElementById("orders") | the element with that id, or null |
document.getElementsByClassName("paid") | every element with that class, as a live HTMLCollection |
document.getElementsByTagName("li") | every element with that tag, as a live HTMLCollection |
document.querySelector(".paid") | the first element matching a CSS selector, or null |
document.querySelectorAll(".paid") | every matching element, as a static NodeList |
document.createElement("li") | a new element, not yet on the page |
parent.append(child) / parent.appendChild(child) | add inside the parent, at the end |
parent.prepend(child) | add inside the parent, at the start |
element.before(other) / element.after(other) | add a neighbour right before or right after |
oldItem.replaceWith(newItem) | put a new element in place of an old one |
parent.replaceChild(newItem, oldItem) | the older replace, called on the parent, new child first |
element.remove() | take the element off the page |
parent.replaceChildren() | delete every child of the parent |
Exercises
What to Remember
- Find, then change.
- Know what each search returns.
- Create, fill, add.
Next: DOM Content Management. Read and change the text, HTML and attributes inside elements.