Introduction to Window and Document Objects

The window and document objects are fundamental in JavaScript for interacting with the browser and web page content. This guide explores their differences, their roles in the Browser Object Model (BOM) and Document Object Model (DOM), and how to use them effectively.

Key Point: The window object is the global container representing the entire browser window, while the document object is a child of window and represents the content of the web page.

Understanding the Window Object

The window object is the top-level object in a browser, representing the browser window or tab. It includes properties and methods for controlling browser-level operations, such as opening new windows, accessing the address bar, or managing timers.

Exploring Window Properties

// Get the inner height of the browser window
console.log(window.innerHeight); // Outputs height in pixels
// Same as above, window can be omitted as it's global
console.log(innerHeight); // Outputs same height
// Access location object
console.log(window.location); // Outputs location object
console.log(location.href); // Outputs current URL

Understanding the Document Object

The document object represents the web page content loaded inside the window. It provides methods to interact with HTML elements, such as selecting elements or modifying their content.

Accessing Document Properties

// Access document object
console.log(window.document); // Outputs document object
// Same as above, window can be omitted
console.log(document); // Outputs document object
// Select an element by ID
const element = document.getElementById('myId');
console.log(element); // Outputs element if found

Browser Object Model (BOM) vs Document Object Model (DOM)

BOM vs DOM

Aspect BOM (Browser Object Model) DOM (Document Object Model)
Scope Represents browser window (e.g., window.location, window.innerHeight) Represents page content (e.g., HTML elements)
Access Accessed via window object Accessed via document object
Examples window.location, window.setTimeout document.getElementById, document.querySelector

Practical Examples

Window and Document in Action

// Get current URL from window.location
console.log(location.href); // Outputs current URL
// Change page title using document
document.title = 'New Title';
console.log(document.title); // Outputs 'New Title'
// Open a new window
window.open('https://example.com'); // Opens new window

Best Practices

  • Omit window when accessing global properties like setTimeout or location for cleaner code.
  • Use document methods like getElementById or querySelector for precise DOM manipulation.
  • Understand the scope: Use window for browser-level operations and document for page content.
  • Test window properties like innerHeight dynamically to account for browser resizing.
  • Be consistent in referencing objects to maintain code readability.