The DOM (Document Object Model) and how JavaScript uses it to read and change web page content, structure, and styles.
What is the DOM?
The DOM represents a web page as a tree of objects. Each HTML element is a node. JavaScript can access these nodes to read or change the page.
Accessing the DOM
Everything starts with the document object, which represents the whole page.
Example – accessing an element
let title = document.getElementById("pageTitle");
console.log(title.innerHTML);
Here JavaScript finds an element by its ID and logs its content.
Manipulating elements
Once you have a reference to an element, you can change it in several ways.
Changing text
title.innerHTML = "New Page Title";
Changing styles
title.style.color = "blue";
Changing attributes
let image = document.getElementById("myImage");
image.src = "path/to/new/image.jpg";
Creating and adding elements
JavaScript can create new elements and insert them into the page.
Example – adding a new element
let newParagraph = document.createElement("p");
newParagraph.innerHTML = "This is a new paragraph.";
document.body.appendChild(newParagraph);
Event handling with the DOM
As covered in the previous article, JavaScript can react to user actions on DOM elements – clicks, input, form submission, and so on.
Example – click event
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
Navigating the DOM tree
The tree structure lets you move between related nodes.
Accessing children
let list = document.getElementById("myList");
let firstItem = list.firstChild;
Accessing parent elements
let listItem = document.getElementById("listItem");
let parentList = listItem.parentNode;
Searching the DOM
Find elements with getElementById, getElementsByClassName, or the more flexible querySelector and querySelectorAll.
Example – querySelector
let specialItems = document.querySelectorAll(".special");
DOM and performance
DOM changes are not free, especially if you do them repeatedly. A few habits help:
- Minimise direct DOM manipulations.
- Use efficient selectors.
- Batch updates rather than changing the DOM on every small step.
AJAX and Fetch API
Modern apps often fetch data from a server and update the page with the result. The Fetch API is the current standard for this.
Example – Fetch API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
document.getElementById("dataContainer").innerHTML = data;
});
The DOM is the link between your JavaScript and the page. Get comfortable with selecting, changing, and adding elements – most interactive web code depends on it.

