JavaScript Location Object

In this chapter you will learn about JavaScript location object. The location object can be use to get the current page URL and to redirect the browser to a new page or reload current page.

Window Location Object

It is not mandatory to prefix window object with location object. It can be write without window object.

Example

  • location.href returns the current page URL
  • location.hostname returns the domain name of the current page
  • location.pathname returns the path and file name of the current page
  • location.protocol returns the protocol(http or https) of the current page
  • location.port return the port number in use.

Location Href

The location.href returns the URL of the current web page.

Example

<!DOCTYPE html>
<html>
<body>

location.href displays current page URL.
<p id="test"></p>

<script>
document.getElementById('test').innerHTML = location.href;
</script>

</body>
</html>

Download the code Run the code

Location Hostname

The location.hostname returns the domain name of the current web page.

Example

<!DOCTYPE html>
<html>
<body>

location.hostname displays current page domain name or host name with port (if specified in URL)
<p id="test"></p>

<script>
document.getElementById('test').innerHTML = location.hostname;
</script>

</body>
</html>

Download the code Run the code

Location Pathname

The location.pathname returns the pathname of the current web page. In URL, anything after domain name starting with slash(/) is called pathname.

http://www.example.com/extra/location/add.php
In above URL, /extra/location is path name

Example

<!DOCTYPE html>
<html>
<body>

location.pathname displays current page path name.
<p id="test"></p>

<script>
document.getElementById('test').innerHTML = location.pathname;
</script>

</body>
</html>

Download the code Run the code

As current page has no pathname set, it returns only / as pathname.

Location Protocol

The location.protocol returns the used protocol of the current web page.

Example

<!DOCTYPE html>
<html>
<body>

location.protocol displays current page protocol. It can be either http: or https:.
<p id="test"></p>

<script>
document.getElementById('test').innerHTML = location.protocol;
</script>

</body>
</html>

Download the code Run the code

Location Hash

The location.hash returns the hash value of the current web page URL. Any value from URL after the # character is hash value. Location Hash value is mostly use for to keep page position after page reload for Ajax content.

Example

<!DOCTYPE html>
<html>
<body>

location.hash displays hash part of current URL.
<p id="test"></p>

<script>
document.getElementById('test').innerHTML = location.hash;
</script>

</body>
</html>

Download the code Run the code

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .