What is the difference between the Window object and the Document object?
Topics
Web APIsJavaScript
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()
, andwindow.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()
andwindow.setInterval()
. - It is the global execution context, meaning all global variables and functions are properties of the
Window
object.
Example:
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()
, anddocument.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
anddocument.URL
. - It can be used to listen for and handle events within the document.
Example:
Key differences
- The
Window
object represents the browser window, while theDocument
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 theDocument
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 theWindow
object. TheDocument
object is a property of theWindow
object.