Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

What is the difference between the Window object and the Document object?

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

The Window object represents the browser window and provides methods to control it, such as opening new windows or accessing the browser history. The Document object represents the content of the web page loaded in the window and provides methods to manipulate the DOM, such as selecting elements or modifying their content.


Difference between the Window object and the Document object

Window object

The Window object is the global object in a web browser environment. It represents the browser window or frame that contains a DOM document. Here are some key points about the Window object:

  • It provides methods to control the browser window, such as window.open(), window.close(), and window.alert().
  • It gives access to the browser's history through window.history.
  • It allows interaction with the browser's location (URL) via window.location.
  • It can be used to set and clear timers with window.setTimeout() and window.setInterval().
  • It is the global execution context, meaning all global variables and functions are properties of the Window object.

Example:

// Open a new window
window.open('https://www.example.com');
// Display an alert
window.alert('Hello, world!');

Document object

The Document object represents the HTML or XML document loaded in the browser window. It is a property of the Window object (window.document). Here are some key points about the Document object:

  • It provides methods to select elements, such as document.getElementById(), document.querySelector(), and document.getElementsByClassName().
  • It allows manipulation of the DOM, including creating, removing, and modifying elements.
  • It provides properties to access the document's metadata, such as document.title and document.URL.
  • It can be used to listen for and handle events within the document.

Example:

// Select an element by its ID
const element = document.getElementById('myElement');
// Change the content of the selected element
element.textContent = 'New content';

Key differences

  • The Window object represents the browser window, while the Document object represents the content of the web page.
  • The Window object provides methods to control the browser window and interact with the browser environment, whereas the Document object provides methods to manipulate the DOM and interact with the content of the web page.
  • The Window object is the global execution context, meaning all global variables and functions are properties of the Window object. The Document object is a property of the Window object.

Further reading

Edit on GitHub