Learnitweb

What is the difference between window and document?

In JavaScript, window and document are both objects that provide access to different parts of the browser’s functionality. Here’s a detailed explanation of their differences:

window object

  • Definition: The window object represents the browser’s window or tab that contains the web page. It is the top-level object in the browser’s JavaScript environment.
  • Global Scope: All global variables and functions are properties of the window object. For example, alert, setTimeout, and location are methods or properties of the window object.
  • Key Properties and Methods:
    • window.alert(): Displays an alert box.
    • window.setTimeout(): Executes a function after a specified delay.
    • window.location: Provides access to the URL of the current page.
    • window.localStorage: Provides access to local storage.
    • window.innerWidth and window.innerHeight: Dimensions of the browser window.
  • Example:
console.log(window.location.href); // Logs the current page URL

document object

  • Definition: The document object is a property of the window object and represents the content of the web page (the DOM – Document Object Model).
  • Access to the DOM: The document object is used to interact with and manipulate the structure and content of the webpage.
  • Key Properties and Methods:
  • document.getElementById(): Selects an element by its ID.
  • document.querySelector(): Selects the first matching element using a CSS selector.
  • document.createElement(): Creates a new HTML element.
  • document.body: Represents the <body> element of the page.
  • document.title: Gets or sets the title of the document.
  • Example:
document.getElementById("myDiv").innerText = "Hello, world!";

Summary of Differences

Featurewindowdocument
RepresentsBrowser window/tabWeb page content (DOM)
ScopeTop-level objectPart of the window object
UsageGeneral browser-related actionsDOM manipulation
Exampleswindow.alert(), window.locationdocument.getElementById(), document.body

Relationship Between Them

The document object is a property of the window object. You can access document as window.document, but typically, it’s just referenced as document for simplicity.

console.log(window.document === document); // true