DOM Basics
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs (like JavaScript) can change the document structure, style, and content. The DOM represents the document as nodes and objects, making it possible for code to interact with the web page dynamically.
1. What is the DOM Tree?
When a web browser loads an HTML document, it creates a hierarchical representation of that document. This structure resembles a tree, known as the DOM Tree.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome</h1>
<p>This is a paragraph.</p>
</body>
</html>
In the DOM tree:
documentis the root node.<html>is the child of the document.<head>and<body>are siblings, children of<html>.- Text inside the tags (like "Welcome") are also considered nodes (Text Nodes).
2. Nodes vs. Elements
It is crucial to understand the distinction between a Node and an Element:
- Node: The generic term for any object in the DOM hierarchy. There are many types of nodes, including:
- Element Nodes (e.g.,
<div>,<h1>) - Text Nodes (the actual text inside elements)
- Comment Nodes (HTML comments
<!-- -->) - The Document Node (the entry point)
- Element Nodes (e.g.,
- Element: A specific type of Node (Node type 1). An element corresponds to an HTML tag. All elements are nodes, but not all nodes are elements.
3. The document Object
The document object is your gateway to interacting with the DOM. It represents the entire HTML document loaded in the browser window and provides properties and methods to traverse, query, and manipulate the tree.
4. Selecting Elements (Querying the DOM)
Before you can change a webpage via JavaScript, you must select the element you want to interact with. JavaScript provides several methods for this:
getElementById()
Selects a single element based on its unique id attribute. Returns null if not found.
// <div id="app-container"></div>
const container = document.getElementById('app-container');
getElementsByClassName()
Returns a live HTMLCollection of all elements that have the specified class name.
// <button class="btn-primary">Submit</button>
const buttons = document.getElementsByClassName('btn-primary');
getElementsByTagName()
Returns a live HTMLCollection of elements with the given tag name.
const allParagraphs = document.getElementsByTagName('p');
querySelector() (Modern & Recommended)
Returns the first element that matches a specified CSS selector. This is highly versatile because you can use any valid CSS syntax (.class, #id, tag, [attribute]).
const mainHeading = document.querySelector('h1');
const submitButton = document.querySelector('.form-submit.btn');
const activeItem = document.querySelector('ul > li.active');
querySelectorAll()
Returns a static NodeList containing all elements that match the specified CSS selector.
const allListItems = document.querySelectorAll('.nav-menu li');
// NodeLists can be iterated over using forEach
allListItems.forEach(item => {
console.log(item.textContent);
});
5. Traversing the DOM
Once you have an element, you can navigate up, down, or sideways in the DOM tree.
Moving Up (Parents)
element.parentNode/element.parentElement: Returns the parent node/element.element.closest(selector): Searches up the DOM tree and returns the closest ancestor matching the selector (including the element itself).
Moving Down (Children)
element.childNodes: Returns a NodeList of all child nodes (including text and comment nodes).element.children: Returns an HTMLCollection of only child Elements (ignores text nodes).element.firstChild/element.firstElementChild: Gets the first child.element.lastChild/element.lastElementChild: Gets the last child.
Moving Sideways (Siblings)
element.nextSibling/element.nextElementSibling: Gets the next sibling.element.previousSibling/element.previousElementSibling: Gets the previous sibling.
Summary
The DOM is the bridge between HTML and JavaScript. Understanding how the browser parses HTML into a Tree of Nodes, and mastering selectors like querySelector and getElementById, is the first step toward building interactive and dynamic web applications.