What is the difference between the document selector and window selector? What is the difference between the document selector and window selector? jquery jquery

What is the difference between the document selector and window selector?


$(window) selector is for selecting the viewport

$(document) selector is for the entire document (that is, what's inside the <html> tag, even if it exapnds beyond the viewport).


While using the window or document object in a jQuery dom selector, most of the time you won't notice a difference between the two.

However, it's important to note that they are not the same object.

window - refers to the viewport. It's used as the main global object in JavaScript.
document - a direct descendant of window; refers to the root of the document tree.

All DOM elements are a descendant of the document, which is a direct descendant of window.


To answer this question let me begin with the definition of the DOM, what we commonly know as "document".

The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense.

Now let me explain a little of what I found about browsing contexts, as that is the relationship that a Document and a Window normally have—although it is important to mention that a Document may exist without a browsing context, but you should never see that with jquery.

A user interacts with the main view of the Document. A view is defined as the media that is being used to present the Document to the user agent—e.g. screen, print, speech. The main view is the default view and is represented by an AbstractView object that implements the Window interface.

And to put it really simple, window is the container and document is the content. But I do recommend to at least skim through the documentation of this to have a better understanding.

Sources: