Browser Object Model and Document Object Model
JavaScript consists of three main components: ECMAScript, DOM (Document Object Model), and BOM (Browser Object Model). While ECMAScript provides the core language features, BOM enables interaction with the browser environment, and DOM allows manipulation of HTML documents.
The Window Object
The window object serves as the top-level object in client-side JavaScript. It represents the browser window and acts as the global scope for all JavaScript variables and functions. All global variables and functions become properties and methods of the window object respectively.
Key properties and methods include:
window.innerHeightandwindow.innerWidth: Retrieve the dimensions of the browser windowwindow.open()andwindow.close(): Control new windows
BOM Components
Navigator Object
Provides information about the user's browser:
navigator.appName // Browser name
navigator.appVersion // Version info
navigator.userAgent // Full user agent string
navigator.platform // Operating system
Screen Object
Contains display information:
screen.availWidth // Available width
screen.availHeight // Available height
History Object
Manages navigation history:
history.forward() // Go forward
history.back() // Go back
Location Object
Represents the current URL and enables navigation:
location.href // Current URL
location.href = "newpage.html" // Navigate
location.reload() // Reload page
Dialog Boxes
JavaScript offers three types of dialog boxes:
alert(message)- Displays a messageconfirm(message)- Prompts for confirmation (returns boolean)prompt(message, default)- Requests user input (returns string or null)
Timing Functions
Control execution based on time intervals:
setTimeout(callback, delay)- Executes once after delayclearTimeout(id)- Cancels a timeoutsetInterval(callback, interval)- Repeats execution at intervalsclearInterval(id)- Stops repeated execution
Example usage:
const timer = setTimeout(() => {
console.log("Delayed execution");
}, 3000);
clearTimeout(timer);
const interval = setInterval(() => {
console.log("Repeated execution");
}, 2000);
clearInterval(interval);
Document Object Model
DOM represents the structure of a HTML document as a tree of nodes. Each element, text, attribute, and comment becomes a node in this model.
Node Types
- Document node: Represents the entire document
- Element nodes: Represent HTML elements
- Text nodes: Contain text content
- Attribute nodes: Represent element attributes
- Comment nodes: Represent HTML comments
Element Selection
Direct selection methods:
document.getElementById("id")
document.getElementsByClassName("class")
document.getElementsByTagName("tag")
Indirect selection using parent/child relationships:
parentElement
children
firstElementChild
lastElementChild
nextElementSibling
previousElementSibling
Node Manipulatino
Creating and appending nodes:
const divElement = document.createElement("div");
const container = document.getElementById("container");
container.appendChild(divElement);
Removing nodes:
const parent = element.parentNode;
parent.removeChild(element);
Replacing nodes:
parent.replaceChild(newNode, oldNode);
Text Content
Accessing and modifying text:
const element = document.getElementById("myDiv");
element.innerText = "New text";
element.innerHTML = "<strong>Bold text</strong>";
Attribute Handling
Setting and retrieving attributes:
const element = document.getElementById("myImg");
element.setAttribute("src", "image.jpg");
element.getAttribute("src");
element.removeAttribute("alt");
// For standard attributes
imgElement.src = "new.jpg";
Form Values
Accessing form field values:
const inputField = document.getElementById("inputField");
const value = inputField.value;
Class Manipulation
Working with CSS classes:
const element = document.getElementById("myElement");
element.className = "newClass";
// Using classList API
element.classList.add("active");
element.classList.remove("hidden");
element.classList.toggle("highlight");
Styling Elements
Direct style modification:
const element = document.getElementById("myElement");
element.style.backgroundColor = "red";
element.style.marginTop = "10px";
element.style.fontFamily = "Arial";
Event Handling
Events are actions that ocurr in the browser. Common events include:
onclick,ondblclickonfocus,onbluronchangeonkeydown,onkeyuponload,onunloadonmousedown,onmousemove,onmouseuponsubmit
Event binding approaches:
- Inline handlers:
<button onclick="handleClick(this)">Click me</button>
function handleClick(element) {
element.style.backgroundColor = "green";
}
- Property assignment:
const button = document.getElementById("myButton");
button.onclick = function() {
this.textContent = "Clicked!";
};
Practical Examples
Search box functionality:
function onFocus() {
const input = document.getElementById("searchInput");
if (input.value === "Enter keyword") {
input.value = "";
}
}
function onBlur() {
const input = document.getElementById("searchInput");
if (!input.value.trim()) {
input.value = "Enter keyword";
}
}
Dropdown cascading:
const cities = {
1: ["Changping", "Chaoyang", "Haidian"],
2: ["Jing'an", "Minhang", "Pudong"]
};
const citySelect = document.getElementById("citySelect");
citySelect.onchange = function() {
const selectedCity = this.value;
const areaSelect = document.getElementById("areaSelect");
// Clear previous options
areaSelect.innerHTML = "";
// Populate new options
cities[selectedCity].forEach(area => {
const option = document.createElement("option");
option.textContent = area;
areaSelect.appendChild(option);
});
};
Working with Styles
Style manipulation can be achieved through class management or direct property modification:
-
Class-based styling:
classNamereturns a string of all classesclassListprovides array-like operations
-
Direct CSS property modification:
- Properties with hyphens require camelCase notation
- Standard properties can be accessed directly
const element = document.getElementById("myElement");
// Style via classList
element.classList.add("highlighted");
// Style via direct property
element.style.backgroundColor = "blue";
element.style.marginTop = "5px";