DOM — Explained with Examples
The DOM (Document Object Model) is a tree-structured representation of HTML that browsers create, enabling JavaScript to dynamically access and modify page content.
The DOM is a programming interface for HTML and XML documents. When a browser loads a page, it parses the HTML into a tree of objects (nodes) — elements, attributes, text, and comments. JavaScript can traverse, query, and modify this tree through the document object. DOM methods include getElementById, querySelector, createElement, and addEventListener.
Think of the DOM like a blueprint of a house. The HTML is the architect’s plan, the browser builds the actual house (renders the page), and the DOM is the complete detailed blueprint of the built house. JavaScript is the contractor who can read the blueprint, find specific rooms, change wall colors, or add new rooms.
DOM manipulation is powerful but has performance costs. Every change can trigger reflow (recalculating layout) and repaint (redrawing pixels). Modern frameworks use virtual DOMs to batch and optimize updates.
// Accessing DOM elements
const header = document.getElementById('header');
const buttons = document.querySelectorAll('.btn');
const firstParagraph = document.querySelector('p');
// Modifying the DOM
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello, DOM!';
newDiv.classList.add('highlight');
document.body.appendChild(newDiv);
// Handling events
button.addEventListener('click', (event) => {
event.target.style.backgroundColor = 'blue';
});
// Traversing the DOM tree
const parent = element.parentNode;
const children = element.children;
const nextSibling = element.nextElementSibling;The DOM is language-agnostic — any language can interact with it if provided with the appropriate bindings. In practice, it is most commonly used with JavaScript in web browsers.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro