document location object in client side javaScript

The document location object in client side javaScript is a read only object that contains the url of the current page. It can be used as a way to know the current url, as well as preform a redirect to a new location. That is because although the object itself is read only a new url can be set to the property that will cause the browser to load that url. So in this post I will be outlining some basic use case examples of the document.location property.

1 - document location basic example

For a basic example of document location here I have a basic html structurer and a single script tag. Inside the script tag I am using the document location href property to display the current htef of the document.

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head>
<title>document location</title>
</head>
<body>
<div id="out"></div>
<script>
let el = document.getElementById('out')
el.innerText = document.location.href;
</script>
</body>
</html>

2 - redirect example

The href property of a location object can also be set to a url, and when doing so will result in a redirect to that url.

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>document location redirect</title>
</head>
<body>
<input value="to google" type="button">
<script>
document.getElementsByTagName('input')[0].addEventListener('click', function(){
document.location.href = 'https://www.google.com/';
});
</script>
</body>
</html>