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

眉间皱痕 提交于 2019-12-03 04:40:39

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.

$(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).

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!