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.
document.domain
Here, the document
object refers to the HTML page we want to render in the browser.
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
.
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.
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 the onclick
event and fires the fetchDomain()
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.domain
property and assign its return value to the domain
variable.
Line 13–14: First, we fetch our placeholder <p>
tag using the document.getElementById()
method. Next, we use the innerHTML
property to populate it with the domain of our web page.
Note: To read more on the
document.getElementBydId()
method and theinnerHTML
property, please refer the following links:
Free Resources