What is the use of document.defaultView property in DOM?

In this Answer, we'll cover the use of the DOM's document.defaultView property. This property retrieves the window object, representing an open window of our browser containing an HTML document.

Syntax


document.defaultView

Here, document refers to the HTML page loaded in our browser.

Return value

The return value of this property is the window object, which can be used to access various methods and properties. In this Answer, we'll look at the innerHeight and innerWidth properties of the window object.

Example

Now let's take a look at a code example that will help us understand how to implement the document.defaultview property:

Explanation

The code example above uses the document.defaultView property to get hold of the window object and is described as follows:

  • Lines 5–9: In this code snippet, the <div> tag encapsulates the web page's content. The HTML elements that are necessary to demonstrate the use of the property in the problem statement are as follows:

    • Line 8: This line displays an HTML <button> listening for the onclick event and triggers the getWindowObject() method.

  • Lines 10–17: These lines of code contain <script> tags, which enclose our getWindowObject() method. The body of the function is made up of the following statements:

    • Line 12: In this line of code, we use the document.defaultView property assign the return value to the variable viewport.

    • Lines 13–14: Here, we are aware that viewport now contains the window object, so we use the viewport.innerHeight and viewport.innerWidth properties and store the dimensions of the viewport inside the variables, height & width.

    • Line 15: Here, we use a JavaScript alert() to display the dimensions to the reader.

Note: To read about the innerHeight & innerWidth properties of the window object, please refer to this Answer.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved