HTML links are very helpful for navigation and are used everywhere on a website. You might need to get the href
value of different links in JavaScript. Here are 2 different methods to get the link or href
value by using JavaScript.
Method 1: Using getAttribute
function to get href
value
You can use the built-in getAttribute
function to get the value of any attribute of an element. This also works for the anchor element to get the link or href
value. The following example get’s the href
value of the element that has “link” as the id.
1 2 3 4 5 6 7 |
const linkElement = document.querySelector("#link"); const link = linkElement.getAttribute("href"); console.log(link) // https://latestjavascript.com/ |
1 2 3 4 5 |
<a href="https://latestjavascript.com" id="link">Our Website</a> |
You can read more about getAttribute
function on mozilla docs.
Method 2: Using Dot .
to Get href
Value of a Link
You can also use the .
notation to get the value of any attribute of an HTML element. As the element is a node and all the properties can be accessed with .
so, you can get the href
value of a link. The following example also gets the href
value of an anchor element.
1 2 3 4 5 6 7 |
const linkElement = document.querySelector("#link"); const link = linkElement.href; console.log(link) // https://latestjavascript.com/ |
Conclusion
You can either use .
to get the href
value after getting the reference to an anchor element or use the getAttribute
function which is built-in to JavaScript. The getAttribute
function can work with any other attribute such as class, src and id.