JavaScript window vs document Object
In JavaScript, the window and document objects are the core of web page interaction. They let you access the browser environment and manipulate the webpage content (DOM).
1. What is the window Object?
The window object is the global object in a browser environment. It represents the browser window/tab and contains everything related to the browser: timers, location, history, alerts, and even the document object itself.
Example:
console.log(window); // Displays the full window object
console.log(window.innerWidth); // Browser width
console.log(window.location.href); // Current page URL
Common window Methods:
Method | Description |
---|---|
alert() | Displays an alert box |
confirm() | Shows confirm box (OK/Cancel) |
prompt() | Prompts user to enter input |
setTimeout() | Runs a function after delay |
setInterval() | Runs function repeatedly at intervals |
open() / close() | Opens or closes a new browser window |
scrollTo() | Scrolls to a specific position |
2. What is the document Object?
The document object is a property of the window object. It represents the DOM (Document Object Model) of the current HTML page — letting you select, update, and manipulate HTML elements.
Example:
console.log(document); // The entire HTML document
console.log(document.title); // Page title
console.log(document.body); // The <body> tag
Common document Methods:
Method | Description |
---|---|
getElementById() | Get element by ID |
querySelector() | Get first match by CSS selector |
createElement() | Create a new HTML element |
appendChild() | Add an element to the DOM |
getElementsByTagName() | Get all elements with the given tag name |
write() | Write HTML directly to the document |
3. Relationship Between window and document
The document object is inside the window object:
console.log(window.document === document); // true
// So technically, you can write:
window.document.getElementById("myDiv");
// OR simply:
document.getElementById("myDiv");
4. Key Differences: window vs document
Feature | window | document |
---|---|---|
Represents | Entire browser window | HTML document inside the window |
Scope | Global object | Part of the window |
Accesses | Browser features (URL, alert, etc.) | DOM (HTML structure) |
Example method | window.alert() | document.getElementById() |
Real-World Use Cases
Use window for:
- Alert boxes
- Redirects (e.g., window.location)
- Timer functions (setTimeout, setInterval)
- Window dimensions or scrolling
Use document for:
- Selecting and updating DOM elements
- Creating or removing HTML content
- Reading form inputs