In this blog post, we will discuss how to use the href attribute in JavaScript to manipulate and navigate through web pages. The
href attribute is commonly used in HTML anchor tags to specify the destination URL of a hyperlink. However, we can also use
JavaScript to set or get the href property of an anchor tag, as well as other elements like the window location object.
Setting href property of an anchor tag
To set the href property of an anchor tag using JavaScript, you can simply assign the desired URL to the href
property of the anchor element. Here’s how you can do this:
<script> // Get the anchor element by its id var anchor = document.getElementById("myAnchor"); // Set the href property to the desired URL anchor.href = "https://example.com"; </script>
Getting href property of an anchor tag
To get the value of the href property of an anchor tag, you can simply access the href property of the
anchor element like this:
<script> // Get the anchor element by its id var anchor = document.getElementById("myAnchor"); // Get the href property value var href = anchor.href; console.log("The href is: " + href); </script>
Setting window location.href
Apart from anchor tags, you can also set the href property of the window location object to navigate to a new
web page. When you set the window.location.href property, the browser will navigate to the provided URL:
<script> // Set the window location href to navigate to a new web page window.location.href = "https://example.com"; </script>
Getting window location.href
To get the current URL of the web page, you can access the window.location.href property like this:
<script> // Get the current URL var currentUrl = window.location.href; console.log("The current URL is: " + currentUrl); </script>
In conclusion, the href attribute plays a crucial role in navigating and manipulating web pages using JavaScript. It can be used
to set or get the destination URL of an anchor tag or to navigate to a new web page using the window location object.