The Location host property returns/sets the hostname and host port (if specified). Port might not get displayed if not explicitly specified.
Syntax
Following is the syntax −
- Returning value of the host property
location.host
- Value of the host property set
location.host = hostname:host
Example
Let us see an example for Location host property −
<!DOCTYPE html> <html> <head> <title>Location host</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } input[type="button"] { border-radius: 10px; } </style> </head> <body> <form> <fieldset> <legend>Location-host</legend> <label for="urlSelect">Current URL:</label> <input type="url" size="27" id="urlSelect" value="https://www.example.com:2544"> <input type="button" onclick="getHostPort()" value="Get Port"> <div id="divDisplay"></div> </fieldset> </form> <script> var divDisplay = document.getElementById("divDisplay"); var urlSelect = document.getElementById("urlSelect"); function getHostPort() { if(location.host.includes(':') === false) divDisplay.textContent = 'No port present, as host: '+location.host; else divDisplay.textContent = 'Port: '+location.host.split(":")[1]+', as host: '+location.host; } </script> </body> </html>
Output
This will produce the following output −
Before clicking ‘Get Port’ button −
After clicking ‘Get Port’ button −