In this article, we will see the Document object & Window object, their various properties & methods, along with knowing their implementation & the differences between them.
Document Object:
The document object represents a web page that is loaded in the browser. By accessing the document object, we can access the element in the HTML page. With the help of document objects, we can add dynamic content to our web page. The document object can be accessed with a window.document or just document.
Syntax:
document.property_name;
The properties of document objects that are commonly used are listed in the below table:
Properties of document:
- activeElement: It returns the currently active elements in the document.
- body: It returns the contents of the body element.
- anchors: It returns all <a> elements that have a name attribute.
- baseURI: It returns a string value that represents the base URI of the document.
- cookie: It returns the cookie of the current document.
- charSet: It returns a string, representing the document’s character encoding.
- defaultView: It returns the current Window Object.
- designMode: It is used to set documents as editable or read-only.
- domain: It returns the domain name of the document server.
- doctype: It returns the document’s doctype.
- embeds: It returns the collection of all embedded elements.
- URL: It returns the complete URL of the document.
- forms: It returns all the elements of the form.
- fullScreenElement: It returns the element that is currently present in full-screen mode.
- title: It returns the title element of the document.
- head: It returns the head element of the document.
- links: It returns all <area> and <a> elements that have a href attribute.
- lastModified: It returns the date and time of the current document that was last modified.
- images: It returns the collection of <img> elements in the document.
- implementation: It returns the DOMImplementation object associated with the current document.
- readyState: It returns the loading status of the current document.
- referrer: It returns the URI of the page that is linked to the current page.
- scripts: It returns all script elements present in the document.
- strictErrorChecking: It sets or returns whether strict error checking can be enforced on a document or not.
Methods of Document
Syntax:
document.method_name;
The lists of most commonly used methods are listed below:
- addEventListener(): It is used to attach an event handler to the specified element.
- adoptNode(): It is used to adopt a node from another document and it returns a node object, representing the adopted node.
- close(): It is used to close the output stream.
- createAttribute(): It is used to create an attribute node with the specified name and returns the attribute object.
- createComment(): It is used to create a comment node with some text.
- createDocumentFragment(): It is used to create the document fragment to change the content of the document.
- createElement(): It is used to create HTML element .
- createEvent(): It is used to create a new events object.
- createTextNode(): It is used to create a textnode.
- execCommand(): It is used to execute a command specified by the user on the editable selected section. It returns a Boolean value.
- fullscreenEnabled(): It is used to check whether the document can be viewed in fullscreen mode or not. It returns a boolean value.
- getElementById(): It returns the object of the given ID. If no object with that id exists then it returns null.
- getElementsByClassName(): It returns an object containing all the elements with the specified class names in the document as objects.
- getElementsByName(): It returns an object containing all the elements with the specified name in the document as objects.
- getElementsByTagName(): It returns an object containing all the elements with the specified tag names in the document as objects.
- hasFocus(): It returns a boolean value that indicates whether the document or element has focus or not.
- importNode(): It imports the copy of a node from another document in the current document.
- normalize(): It flushes out the empty nodes and merges the adjacent text nodes with the first text node and
- normalizeDocument(): It is used to normalize an HTML document by removing any empty text nodes and joining the adjacent text nodes.
- open(): It is used to open the output stream to collect the output.
- querySelector(): It returns the first element that matches a specified CSS selector(s) in the document.
- querySelectorAll(): It returns a collection of an element’s child elements that matches a specified CSS selector(s) in the document
- removeEventListener(): It removes the event handler from an element that has an attached event.
- renameNode(): It is used to rename the node.
- write(): It is used to write some content or javascript code in the document.
- writeln(): It is used to write a document with a newline character after each statement.
Example: This example describes the implementation of the document.object.
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>document's Properties</
title
>
<
style
>
h1 {
color: green;
}
</
style
>
</
head
>
<
body
>
<
h1
> GeeksforGeeks</
h1
>
<
button
onclick
=
"myFunction()"
>CLICK ME</
button
>
<
p
id
=
"demo"
></
p
>
<
script
>
function myFunction() {
let title = document.title;
let domain = document.domain;
let body = document.body;
document.getElementById("demo").innerHTML =
"the title of the document is : "
+ title
+ "<
br
>"
+ "domain : "
+ domain
+ "<
br
>"
+ "body : "
+ body;
}
</
script
>
</
body
>
</
html
>
Output:
Window Object
The window object is the topmost object of the DOM hierarchy. It represents a browser window or frame that displays the contents of the webpage. Whenever a window appears on the screen to display the contents of the document, the window object is created.
Syntax:
window.property_name;
The properties of Window objects that are commonly used are listed in the below table:
Properties of the window:
- Closed: It holds a Boolean value that represents whether the window is closed or not.
- console: It returns a reference to the console object which provides access to the browser’s debugging console.
- defaultStatus: It is used to define the default message that will be displayed in the status bar when no activity is carried on by the browser.
- controllers: It returns the XUL controller objects for the current Chrome window.
- customElements: It returns a reference to the CustomElementRegistry object, which can be used to register new custom elements and also get information about already registered custom elements.
- crypto: It returns the browser crypto object.
- devicePixelRatio: It returns the ratio between physical pixels and device-independent pixels in the current display.
- Document: It returns a reference to the document object of that window.
- DOMMatrix: It returns a reference to a DOMMatrix object, which represents 4×4 matrices, suitable for 2D and 3D operations.
- frames[]: It represents an array that contains all the frames of a given window.
- DOMPoint: It returns a reference to a DOMPoint object, which represents a 2D or 3D point in a coordinate system.
- History: It provides information on the URLs visited in the current window.
- Length: It represents the number of frames in the current window.
- DOMRect: It returns a reference to a DOMRect object, which represents a rectangle.
- fullScreen: This property indicates whether the window is displayed on full screen or not.
- Location: It contains the URL of the current window.
- innerHeight: It is used to get the height of the content area of the browser window.
- innerWidth: It is used to get the width of the content area of the browser window.
- Name: It contains the name of the referenced window.
- Window: It returns the current window or frame.
- Navigator: It returns a reference to the navigator object.
- outerHeight: It will get the height of the outside of the browser window.
- outerWidth: It will get the width of the outside of the browser window.
- Status: It overrides the default status and places a message in the status bar.
- Top: It returns a reference to the topmost window containing a frame if many windows are opened.
- Toolbar: It will result in the toolbar object, whose visibility can be toggled in the window.
- Opener: It contains a reference to the window that opened the current window.
- Parent: It refers to the frameset in which the current frame is contained.
- Screen: It refers to the screen object
- Self: It provides another way to refer to the current window.
Methods of Window:
Syntax:
window.method_name;
The methods of Window objects that are commonly used are listed in the below table:
- alert(): It is used to display an alert box. It displays a specified message along with an OK button and is generally used to make sure that the information comes through the user.
- atob(): It is used for decoding a base-64 encoded string. It is used to decode a string of data that has been encoded using the btoa() method.
- blur(): It is used to remove focus from the current window.
- btoa(): It is used for encoding a string in base-64 format.
- clearInterval(): It clears the interval which has been set by the setInterval() function before that.
- clearTimeout(): It clears the timeout which has been set by the setTimeout()function before that.
- close(): It is used for closing a certain window or tab of the browser which was previously opened.
- confirm(): It is used to display a modal dialog with an optional message and two buttons i.e. OK and Cancel. It returns true if the user clicks “OK”, and false otherwise.
- focus(): It is used to give focus to an element in the current window.
- getComputedStyle(): It is used to get all the computed CSS properties and values of the specified element.
- getSelection(): It returns a Selection object representing the range of text selected by the user
- matchMedia(): It is used to return a MediaQueryList object which represents the result of the specified CSS media query string.
- open(): It is used to open a new tab or window with the specified URL and name.
- moveBy(): It is used for moving a window with a specified number of pixels relative to its current coordinates.
- moveTo(): It is used in the window to move the window from the left and top coordinates.
- prompt(): It is used to display a dialog with an optional message prompting the user to input some text
- resizeBy(): It is used to resize a window by the specified amount.
- resizeTo(): It is used to resize a window to the specified width and height.
- scrollBy(): It is used to scroll the document by the given number of pixels.
- scrollTo(): It is used to scroll to a particular set of coordinates in the document.
- setInterval(): It repeats a given function at every given time interval.
- setTimeout(): It executes a function, after waiting a specified number of milliseconds.
- stop(): It is used to stop the window from loading resources in the current browsing context.
Example: This example describes the implementation of the window.object.
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
title
> Window's Properties</
title
>
<
style
>
h1 {
color: green;
}
</
style
>
</
head
>
<
body
>
<
h1
>GeeksforGeeks</
h1
>
<
button
onclick
=
"show()"
>Check</
button
>
<
p
id
=
"prop"
></
p
>
<
script
>
function show() {
let h = window.innerHeight;
let w = window.innerWidth;
let l = window.location;
let c = window.closed;
document.getElementById("prop").innerHTML =
"Frame's Height: "
+ h + "<
br
>"
+ "Frame's Width: "
+ w + "<
br
>"
+ "Window location:"
+ l
+ "<
br
>"
+ "Window Closed: "
+ c;
}
</
script
>
</
body
>
</
html
>
Output:
Difference between document and window:
document |
window |
---|---|
It represents any HTML document or web page that is loaded in the browser. |
It represents a browser window or frame that displays the contents of the webpage. |
It is loaded inside the window. |
It is the very first object that is loaded in the browser. |
It is the object of window property. |
It is the object of the browser. |
All the tags, elements with attributes in HTML are part of the document. |
Global objects, functions, and variables of JavaScript are members of the window object. |
We can access the document from a window using the window. document |
We can access the window from the window only. i.e. window.window |
The document is part of BOM (browser object model) and dom (Document object model) |
The window is part of BOM, not DOM. |
Properties of document objects such as title, body, cookies, etc can also be accessed by a window like this window. document.title |
Properties of the window object cannot be accessed by the document object. |
syntax: document.propertyname; |
syntax: window.propertyname; |
example: document.title : will return the title of the document |
example: window.innerHeight : will return the height of the content area of the browser |
Last Updated :
20 Jul, 2023
Like Article
Save Article
In console, by writing
this
or
window
and hitting Enter, we can access the window
which is the top level object in the browser — or even by using either one of those properties of window, too:
top
parent
self
globalThis
even combined in between.
Indeed, checking any pair of those above will return true
:
this === window
// true
window === globalThis
// true
this === self
// true
parent === window
// true
top === parent
// true
even some multiple combinations of them — fact possible for the reason that
window.window === window
// true
because window
is also its own property, so we can even write window.window.window === window
as well, or even stuff like window.window.self.top.parent.globalThis === window
, all those returning true
.
The only exception is that we can’t use this
on the last position because it isn’t a property (therefore window.window.this === window
// false because actually window.this === undefined
// true, as window
has NOT a such this property).
As a result, we can’t write self.this
, top.this
, parent.this
, window.this
, the only way possible being to replace it instead with globalThis
in the last position, as a property of window
, like in top.globalThis
etc.
When having a webpage with frames, each frame document would belong to an own separate window object, that separate window being a child of the previous top level window shown earlier — you can simply test that on a platform with frames (like jsfiddle, codepen, w3schools) where writing and executing in the frame console.log(window.parent === window);
will return false
while if you write window.parent === window
directly in console will return true
. In the frame, window.parent
will access the global window (the parent of frame window object being obviously not the same as the frame window object itself). You can check content of each these windowS separately running in the frame the codes (and seeing results like):
console.log(window.document.all);
// HTMLAllCollection(6) [html, head, body, p#demo, button, script, demo: p#demo]
respectively
console.log(window.parent.document.all);
// HTMLAllCollection(335) [html, head, script, script, title, meta, meta, meta, meta, meta, meta, meta, meta, link, link, link, link, script, script, script, script, script, script, script, script, script, style, script, script, script, script, style, script, meta, meta, meta, meta, meta, meta, meta, meta, script, argprec0, argprec1, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, …] — therefore much more elements contained in the parent document
Doing same check, but from the console this time:
window.document.all
// HTMLAllCollection(335) [html, head, script, script, title, meta, meta, meta, meta, meta, meta, meta, meta, link, link, link, link, script, script, script, script, script, script, script, script, script, style, script, script, script, script, style, script, meta, meta, meta, meta, meta, meta, meta, meta, script, argprec0, argprec1, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, …] — again the same huge elements list
As we see, the console (open it with F12) has access to the most top level window scope / context (versus the frame underneath that is contained in its own limited context / scope) so it shows all elements at once. This is same context we started to refer in the beginning as well.
Going further with the main concepts, there is even more to understand.
In saying that window
is the top level object in browser one should understand that it is a certain representation in the memory of the browser (software called client) from where the browser will paint (render) the visible page (which we refer to as a document — again, accesible as a property of window
).
As such, we can access the document
in console — to see its structure — simply using window.document
where we can see everything in it by clicking on #document
. Again, we will see there a representation of the document, not the document itself. That representation seen in console is the DOM, being a Model of the original file, and is created by taking PLUS improving in a certain way, where needed, the data parsed from source code of the original document by the JavaScript engine of the browser. The source code is immutable (the browser doesn’t change the html file received from internet), while the DOM is mutable (and the mutations are made by JavaScript code ran into the browser either before or after the page is rendered on the device hardware). For clarity: what we see in console is DOM, what we see in browser is the rendering and what we see in source code is the original file. They’re not the same, everyone is different from the other two.
To help you understand, I would compare that process with client software being in «real life» some talented person visiting the Louvre museum and seeing the Monalisa painting (the source code file). The image of Monalisa in tourist mind isn’t the same as the original painting made by Leonardo, it’s just a mental representation of it. From it, the talented tourist will then recreate again on his brain some «own» Monalisa, improving here and there what should be improved or changed before finally painting when back at home on a canvas all the colors of the original image plus even more.
Therefore, we have 3 ‘entities’ (a- html file, immutable, containing the source code, b- one representation of it, created after the source code is parsed and «understood» by the browser or improved, c- the rendering itself that is displayed on the screen). The primary improvement mentioned can be like adding closing tags where missing previously in the source file, adding or deleting elements inside the Model, according to the script instructions contained in the source file, changing them, requesting further resources (as images, fonts, css files, media files to be used as assets of the final full page, etc) and so on.
Despite of similarity in names, a window related to a specific document and browser window shouldn’t be considered as the same thing, the first one being attached to the later one (and accesible as a property of it). Likewise, when having multiple browser windows (say 10 instances), each one with multiple tabs (or not), those are attached to the browser window, and their objects accesible by window[0]
up to window[9]
.
Regarding the screen, browser client is a software (a code) that runs and executes another software (source code) for the purpose of finally displaying that (second) code on the hardware device (monitor / screen) through several layers. For this purpose, browser software has also actually its own separate programming routines able to interact with the operating system in order to detect the screen resolution, size, color depths, some settings and more, therefore it acts as a bridge between the operating system and the files meant to be displayed on its rendering area.
Using console.log(window.screen)
will return to us the details collected from the OS by the browser about the device monitor (and stored in its memory) such as {availWidth: 1920, availHeight: 1040, width: 1920, height: 1080, colorDepth: 24, …}
A simpler code can be used (no need to write always the window
word) and extract for example the width of the device:
console.log(screen.width) // 1920
You can use such data even for executing some pseudo media queries based purely on JavaScript and with no CSS whatsoever — for example
function goMobile() {
if (screen.width < 900) {location.replace("/index-mobile.html");}
}
goMobile();
As a conclusion: window
and document
belong to DOM, screen
doesn’t. You need all of them, however because document
and screen
are both properties of window
object, you can just invoke them directly in your code (shortening the code). More, screen
being about the hardware part, not any browsers’ rectangular available area to render on, it hasn’t the meaning of document.body
. At most, you can put screen
data to use in order to optimize your loading page, for example limiting the assets downloads for a better mobile device experience and so on.
What is a JavaScript window?
The window is at a root/top level at the JavaScript object hierarchy. It is a global/root object in JavaScript and it is the root object of the Document object model(DOM);
What is a JavaScript document?
A document is an object inside the window object and we use a document object for manipulation inside the document.
The first thing that gets loaded into the browser is the window and the properties related to that window are stored in the window object. Properties related to window objects are length, innerWidth, innerHeight, caches, etc.
There was a document object too so what about it then?
So after the window gets loaded then there’s a document (HTML, PHP, or another document) loaded inside that window, and the properties related to that document is stored in the document object. Properties related to document objects are title, URL, cookie, etc.
Syntax:
- window object:
window.propertyname;
- document object:
document.propertyname // OR window.document.propertyname
Example 1: Focus on the window object.
Javascript
<!DOCTYPE html>
<html lang=
"en"
>
<head>
<meta charset=
"UTF-8"
>
<meta http-equiv=
"X-UA-Compatible"
content=
"IE=edge"
>
<meta name=
"viewport"
content=
"width=device-width, initial-scale=1.0"
>
<title>Document</title>
</head>
<body>
<h1></h1>
<p id=
"innerheight"
></p>
<p id=
"innerwidth"
></p>
<script>
window.document.bgColor =
"aqua"
;
const height = document.getElementById(
'innerheight'
);
const width = document.getElementById(
'innerwidth'
);
window.document.querySelector(
'h1'
).textContent =
"Welcome to window object"
;
height.textContent =
"innerheight - "
+
window.innerHeight;
width.textContent =
"innerwidth - "
+
window.innerWidth;
</script>
</body>
</html>
Output:
focused on the window object
Example 2: Focus on the document object.
HTML
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
meta
http-equiv
=
"X-UA-Compatible"
content
=
"IE=edge"
>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
>
<
title
>Document object</
title
>
</
head
>
<
body
style
=
"color:white"
>
<
h1
></
h1
>
<
p
class
=
"details"
></
p
>
<
p
class
=
"details"
></
p
>
<
p
class
=
"details"
></
p
>
<
script
>
document.bgColor = "rgb(89, 135, 235)";
const text = prompt('enter the text to appear on screen');
const h1 = document.querySelector('h1');
h1.textContent = text;
const p = document.getElementsByClassName('details');
p[0].textContent = "document type:" +
document.contentType;
p[1].textContent = "url :" + document.bgColor;
p[2].textContent = "title :" + document.title;
</
script
>
</
body
>
</
html
>
Output:
focused on the document object
Document |
Window |
It represents the document loaded inside the window or browser. | It represents the browser window in which you are seeing the content. |
The properties related to it are stored in the document object. | The properties related to it are stored in the window object. |
It is loaded after the loading window because the window contains a document. | It is loaded before the document because window container document. |
It is the root element of the document object model. | The window is the global element for all objects, functions, etc. |
It is an object of window. | It is an object of the browser. |
We can not access windows objects properties inside the document. | We can access document object properties inside the window. |
logically: document:{ properties} |
logically: window:{ |
Example: document.title will return the title of the document | Example: window.document.title will return the title of the document. |
Last Updated :
04 Apr, 2022
Like Article
Save Article
В данной статье мы рассмотрим иерархию объектов в javascript. Объекты window и document в JavaScript играют крайне важную роль и понимание их назначения является необходимым для разработчика.
window — содержит свойства и методы для управления окном браузера.
document — позволяет работать с содержимым страницы.
Объектная модель документа (DOM)
Объектная модель браузера (BOM)
Реализация в jQuery
1 2 3 4 5 6 7 |
$(document).ready(function(){ // сформирован DOM, за исключением загрузки картинок и других ресурсов }) или $(function() { }); |
1 2 3 |
$(window).load(function(){ // когда загружен весь документ, включая картинки, стили, скрипты }) |
1 2 3 |
$(window).resize(function(){ // изменение размеров экрана }) |
1 2 3 |
$(window).scroll(function(){ // отслеживание положения полосы прокрутки }) |
Реализация на чистом JavaScript
DOMContentLoaded – сформирован DOM, за исключением загрузки картинок и других ресурсов
load – когда загружен весь документ, включая картинки, стили, скрипты
Пример реализации DOMContentLoaded:
1 2 3 4 |
document.addEventListener("DOMContentLoaded", function(){ // тело функции // не кроссбраузерное решение (нет поддержки в старых ie) Использовать js библиотеки например jQuery }); |
Пример реализации load:
1 2 3 |
window.onload = function() { // вешается на объект window }; |
Scroll на JavaScript
// положение элемента относительно верхнего края экрана осуществляется с помощью свойства scrollTop
1 2 3 |
window.onscroll = function() { } |
В чём отличия document от window при обработке событий?
-
Вопрос задан
-
3242 просмотра
Комментировать
Пригласить эксперта
Ответы на вопрос 1
А как вы думаете?
window — окно браузера
document — это содержимое всего сайта
Откройте панель разработчика прям щас и вбейте в консоль window и document. Увидите различия
Комментировать
Похожие вопросы
-
Показать ещё
Загружается…
08 окт. 2023, в 23:50
5000 руб./за проект
08 окт. 2023, в 21:59
1000 руб./в час
08 окт. 2023, в 20:00
10000 руб./за проект