2 Ways to Get Link or href Value in JavaScript

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 hrefvalue of the element that has “link” as the id.

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.



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.

Latest articles

Related articles