Understanding JavaScript's DOM and BOM: Core Concepts and Practical Usage
Architecture Overview
JavaScript's runtime environment consists of three main components:
- ECMAScript: The core language specification
- BOM (Browser Object Model): Manages browser operations beyond the page
- DOM (Document Object Model): Handles page content manipulation
Browser Object Model (BOM)
window Object
The window object serves as the parent for most other browser objects, so explicit window references are often optional.
Key window methods and properties:
window.innerHeight // Internal viewport height
window.innerWidth // Internal viewport width
window.close() // Close current window
window.open() // Open new window
navigator Object
The navigator object provides information about the client's browser:
navigator.appName // Full browser name
navigator.appVersion // Browser version details
navigator.userAgent // Client environment information
navigator.platform // Operating system
screen Object
screen.availWidth // Available screen width
screen.availHeight // Available screen height
history Object
history.length // Number of URLs in history
history.forward() // Load previous URL
history.back() // Load next URL
location Object
location.href // Get current URL
location.href = "https://example.com" // Navigate to URL
location.reload() // Reload current page
Dialogs and Timers
// Alert dialog (one-time display)
alert("Message here");
// Single-use timer: executes after 3 seconds
const timeoutId = setTimeout(() => alert("Timeout triggered"), 3000);
clearTimeout(timeoutId);
// Interval timer: executes every 3 seconds
const intervalId = setInterval(() => alert("Interval triggered"), 3000);
clearInterval(intervalId);
Document Object Model (DOM)
The DOM represents every component of an HTML document as a node.
Element Selection
Direct Selection
// By ID
document.getElementById("elementId");
// By class name (returns collection)
document.getElementsByClassName("className")[0];
// By tag name
document.getElementsByTagName("div");
// By CSS selector (returns first match)
document.querySelector(".className");
// By CSS selector (returns all matches)
document.querySelectorAll("div.className");
Common pitfall: Elements not found often results from script executing before DOM is ready. Solutions:
// Place script after target elements, or at end of body
// Alternative: wrap in load event
window.addEventListener("load", function() {
// DOM manipulation code here
});
Indirect Selection (Traversal)
element.parentElement // Parent node
element.children // Child elements collection
element.firstElementChild // First child element
element.lastElementChild // Last child element
element.nextElementSibling // Next sibling
element.previousElementSibling // Previous sibling
DOM Manipulation
// Create element
const newImg = document.createElement("img");
newImg.setAttribute("src", "photo.jpg");
// Find parent container
const container = document.querySelector(".container");
// Append to parent
container.appendChild(newImg);
// Insert before specific child
container.insertBefore(newImg, container.lastElementChild);
// Remove child
container.removeChild(container.firstElementChild);
// Replace child
container.replaceChild(newImg, container.firstElementChild);
Text and HTML Content
const targetDiv = document.getElementById("target");
targetDiv.innerText // Plain text only (no HTML parsing)
targetDiv.innerHTML // HTML content (parses and renders)
// Setting content
targetDiv.innerText = "Plain text content";
targetDiv.innerHTML = "<strong>Bold text</strong> with <em>formatting</em>";
Attribute Management
const box = document.querySelector(".box");
// Custom attributes
box.setAttribute("data-id", "42");
box.getAttribute("data-id");
box.removeAttribute("data-id");
// Native properties (accessible directly)
const image = document.querySelector("img");
image.src = "new-image.jpg";
console.log(image.src);
Value Retrieval
// For input, select, and textarea elements
const inputField = document.getElementById("username");
const userInput = inputField.value;
Class Manipulation
const card = document.querySelector(".card");
card.className // Get all classes as string
card.classList.remove("active") // Remove class
card.classList.add("highlighted") // Add class
card.classList.contains("dark") // Check class exists
card.classList.toggle("expanded") // Toggle class on/off
CSS Style Manipulation
const element = document.getElementById("box");
// Inline styles (use camelCase for CSS properties)
element.style.backgroundColor = "#ff0000";
element.style.marginTop = "20px";
element.style.borderLeftWidth = "5px";
Event Handling
Common Events Reference
| Event | Description |
|---|---|
| click | Mouse click |
| dblclick | Double click |
| focus | Element receives focus (input fields) |
| blur | Element loses focus (form validation trigger) |
| change | Content changes (inputs, select dropdowns) |
| keydown | Key pressed down |
| keypress | Key pressed and released |
| keyup | Key released |
| load | Page or resoruce finished loading |
| mousedown | Mouse button pressed |
| mousemove | Mouse movement |
| mouseout | Mouse leaves element (including child elements) |
| mouseleave | Mouse leaves element (parent only) |
| mouseover | Mouse enters element |
| select | Text selected in input/textarea |
| submit | Form submission triggered |
| input | Real-time input value changes |
Event Binding Approaches
// Method 1: HTML attribute with handler function
// HTML: <div id="clickTarget">Click me</div>
function handleClick(element) {
element.style.backgroundColor = "#00ff00";
}
// In HTML: onclick="handleClick(this)"
// Method 2: DOM property assignment
const target = document.getElementById("clickTarget");
target.onclick = function() {
this.textContent = "Clicked!";
};
// Method 3: addEventListener (recommended)
target.addEventListener("click", function(event) {
this.textContent = "Clicked!";
});
Preventing Default Behavior
// Option 1: Return false from handler
form.onsubmit = function() {
// validation logic
return false;
};
// Option 2: Use preventDefault method
form.addEventListener("submit", function(e) {
e.preventDefault();
// handle submission
});
Event Propagation (Bubbling)
When both parent and child elements have click handlers, clicking the child triggers both. To stop propagation:
childElement.addEventListener("click", function(e) {
e.stopPropagation();
// only this handler executes
});
To capture events in the capturing phase instead of bubbling phase:
parentElement.addEventListener("click", handler, true); // capturing phase