What is the use of the document.domain property in DOM?
In this Answer, we'll explore the DOM's document.domain property. This property provides us with the domain of the server where our web page is hosted or loaded. We'll look at all the necessary details regarding this property and its syntax, along with a code example.
Note: To read about the domain of a web page, please refer to this Answer.
Syntax
document.domain
Here, the document object refers to the HTML page we want to render in the browser.
Return value
The return value of this property is a string, which represents the server's domain name.
Note: If the domain of a web page is not identified, the property returns
null.
Example
Let's look at a code example to further elaborate on the use of this property. Here, we'll fetch the domain of our web page as the reader clicks on the button shown in the output tab.
Explanation
The explanation that follows from the code example above is given below:
Lines 5–9: In this code snippet, we have a
<div>tag that encloses the content of our web page. The content is made using different HTML elements with some important ones mentioned below:Line 7: Here, a placeholder
<p>tag will render the web page's domain when the reader clicks on the<button>present on line 8.Line 8: In this line, we have a
<button>tag that listens for theonclickevent and fires thefetchDomain()method.
Lines 10–16: In these lines of code, we have our actual JavaScript code encapsulated using HTML
<script>tags. The code is explained below:Line 12: In this line, we use
document.domainproperty and assign its return value to thedomainvariable.Line 13–14: First, we fetch our placeholder
<p>tag using thedocument.getElementById()method. Next, we use theinnerHTMLproperty to populate it with the domain of our web page.
Note: To read more on the
document.getElementBydId()method and theinnerHTMLproperty, please refer the following links:
Free Resources