Browser Object Model (BOM)
The Browser Object Model (BOM) represents everything provided by the browser (outside the document). It gives access to the browser window, screen details, navigation, location, alerts, and more. Unlike the DOM, which handles page content, the BOM handles the browser environment itself.
Window Object
The window object is the root of the BOM. All global variables and functions
are properties of the window.
// Window dimensions
console.log(window.innerWidth); // width of viewport
console.log(window.innerHeight); // height of viewport
// Opening a new window
window.open("https://www.example.com", "_blank");
// Alerts and prompts
window.alert("Hello from BOM!");
const name = window.prompt("Enter your name:");
console.log(name);
Location Object
The location object gives details about the current URL and allows
navigation to new pages.
// Get current URL
console.log(window.location.href);
// Redirect to another page
window.location.href = "https://www.google.com";
// Reload the page
window.location.reload();
Navigator Object
The navigator object provides information about the browser and user environment.
// Browser details
console.log(navigator.userAgent);
// Online/Offline status
console.log(navigator.onLine); // true or false
Screen Object
The screen object gives information about the user's screen.
// Screen details
console.log(screen.width); // screen width
console.log(screen.height); // screen height
History Object
The history object lets you navigate through the browser session history.
// Move back and forward
history.back(); // previous page
history.forward();// next page
What is the Document Object Model (DOM)?
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.
Tree Structure
The DOM represents documents as a tree structure where each node is an object representing a part of the document.
Programming Interface
The DOM provides a programming interface that allows scripts to access and update the content, structure, and style of documents.
Cross-Platform
The DOM is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML, and XML documents.
Why is the DOM Important?
The DOM is fundamental to web development because it enables JavaScript to access and manipulate the content and structure of web pages in real time. Without the DOM, web pages would be static and unable to respond to user interactions.
// Example: Accessing DOM elements
const heading = document.getElementById('main-heading');
const paragraphs = document.getElementsByTagName('p');
const buttons = document.querySelectorAll('.btn');
// Example: Changing content
heading.textContent = 'New Heading Text';
heading.style.color = 'blue';
DOM Tree Structure
The DOM represents an HTML document as a tree of nodes. This tree structure is often referred to as the DOM tree. Each branch of the tree ends in a node, and each node contains objects.
How the DOM Tree Works
The DOM tree is structured as a hierarchy of nodes, with the document node at the root. Each node has properties and methods that allow you to traverse and manipulate the tree.
// Example: Traversing the DOM tree
const root = document.documentElement; // Root html element
const head = document.head; // Head element
const body = document.body; // Body element
// Accessing child nodes
const firstChild = body.firstChild;
const lastChild = body.lastChild;
const children = body.children; // HTMLCollection of elements
// Accessing parent node
const parent = body.parentNode; // html element
DOM Node Types
The DOM consists of several different types of nodes. Understanding these node types is essential for effective DOM manipulation.
| Node Type | Description | Example |
|---|---|---|
| Element Node | Represents an HTML element | <div>, <p>, <span> |
| Text Node | Contains the text content of an element | "Hello World" |
| Comment Node | Represents an HTML comment | <!-- This is a comment --> |
| Document Node | Represents the entire document | document |
| Document Type Node | Represents the document type declaration | <!DOCTYPE html> |
Working with Node Types
Each node type has specific properties and methods. You can check the node type using the nodeType property.
// Example: Checking node types
const element = document.querySelector('p');
const textNode = element.firstChild;
console.log(element.nodeType); // 1 (Element node)
console.log(textNode.nodeType); // 3 (Text node)
// Common node type constants
console.log(Node.ELEMENT_NODE); // 1
console.log(Node.TEXT_NODE); // 3
console.log(Node.COMMENT_NODE); // 8
DOM Traversal
DOM traversal refers to navigating through the DOM tree, moving from one node to another based on their relationships.
Parent Nodes
Access the parent of a node using parentNode or parentElement.
Child Nodes
Access children of a node using childNodes, children, firstChild, or lastChild.
Sibling Nodes
Access siblings of a node using previousSibling, nextSibling, previousElementSibling, or nextElementSibling.
DOM Traversal Examples
// Example: DOM traversal methods
const element = document.getElementById('example');
// Access parent
const parent = element.parentNode;
// Access children
const firstChild = element.firstChild;
const lastChild = element.lastChild;
const children = element.children;
// Access siblings
const previousSibling = element.previousElementSibling;
const nextSibling = element.nextElementSibling;
// Using querySelector for complex traversal
const nestedElement = element.querySelector('.nested-class');
DOM Manipulation
DOM manipulation is the process of modifying the document structure, style, or content using JavaScript.
Creating and Adding Elements
// Example: Creating and adding elements
const newDiv = document.createElement('div');
newDiv.className = 'new-class';
newDiv.textContent = 'This is a new div';
// Adding to the DOM
const container = document.getElementById('container');
container.appendChild(newDiv);
// Inserting before an element
const referenceElement = document.getElementById('reference');
container.insertBefore(newDiv, referenceElement);
// Using insertAdjacentHTML for more control
container.insertAdjacentHTML('beforeend', '<p>New paragraph</p>');
Removing and Replacing Elements
// Example: Removing and replacing elements
const elementToRemove = document.getElementById('remove');
// Removing an element
elementToRemove.parentNode.removeChild(elementToRemove);
// Or using modern approach:
elementToRemove.remove();
// Replacing an element
const newElement = document.createElement('div');
newElement.textContent = 'Replacement content';
const oldElement = document.getElementById('old');
oldElement.parentNode.replaceChild(newElement, oldElement);
DOM Events
DOM events are actions that occur in the browser, such as user interactions (clicks, keypresses) or browser events (page load, resize).
Event Handling
// Example: Adding event listeners
const button = document.getElementById('myButton');
// Using addEventListener (recommended)
button.addEventListener('click', function(event) {
console.log('Button clicked!');
event.preventDefault(); // Prevent default behavior
});
// Using inline event handlers (not recommended)
// <button onclick="handleClick()">Click me</button>
// Event delegation example
const list = document.getElementById('myList');
list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
console.log('List item clicked: ' + event.target.textContent);
}
});
Common DOM Events
| Event Type | Description | Example Events |
|---|---|---|
| Mouse Events | Events related to mouse interactions | click, dblclick, mousedown, mouseup, mousemove |
| Keyboard Events | Events related to keyboard interactions | keydown, keyup, keypress |
| Form Events | Events related to form elements | submit, change, focus, blur, input |
| Window Events | Events related to browser window | load, resize, scroll, hashchange |
DOM Performance
Efficient DOM manipulation is crucial for web performance. Poorly optimized DOM operations can lead to slow page rendering and janky user experiences.
Performance Best Practices
Batch DOM Changes
Make multiple changes offline before adding to the DOM to minimize reflows.
Use DocumentFragment
Use DocumentFragment for complex DOM manipulations to avoid excessive reflows.
Efficient Selectors
Use efficient selectors and cache references to DOM elements.
// Example: Using DocumentFragment for better performance
const fragment = document.createDocumentFragment();
// Add multiple elements to the fragment
for (let i = 0; i < 100; i++) {
const li = document.createElement('li');
li.textContent = 'Item ' + i;
fragment.appendChild(li);
}
// Add the fragment to the DOM in a single operation
const list = document.getElementById('myList');
list.appendChild(fragment);
// Example: Debouncing scroll events for performance
function debounce(func, wait) {
let timeout;
return function() {
const context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
func.apply(context, args);
}, wait);
};
}
window.addEventListener('scroll', debounce(function() {
console.log('Scrolled!');
}, 250));
Interactive DOM Demo
Try these interactive examples to see DOM manipulation in action. Experiment with adding, modifying, and removing DOM nodes to understand how the DOM works.
DOM Tree Visualization
JavaScript Code
// Function to add a new node
function addNewNode() {
const newNode = document.createElement('div');
newNode.className = 'dom-node element-node';
newNode.innerHTML = '<div>New Node</div>';
const container = document.getElementById('dom-tree-view');
container.appendChild(newNode);
}
// Function to change node colors
function changeNodeColor() {
const nodes = document.querySelectorAll('.dom-node');
nodes.forEach(node => {
node.style.borderLeftColor =
getRandomColor();
});
}
// Function to remove the last node
function removeLastNode() {
const container = document.getElementById('dom-tree-view');
if (container.lastChild) {
container.removeChild(container.lastChild);
}
}