Get href value of an anchor tag with JavaScript/jQuery
This post will discuss how to get the href value of an anchor tag in JavaScript and jQuery.
1. Using jQuery
In jQuery, you can use the .prop() method to get the href value of an anchor tag. This is demonstrated below:
JS
|
1 2 3 4 5 6 |
$(document).ready(function() { $('#submit').click(function() { var href = $('a').prop('href'); alert(href); }) }); |
HTML
|
1 2 3 4 5 6 7 8 |
<!doctype html> <html> <body> <a href="https://www.bing.com/">Click Me</a> <br><br> <button id="submit">Submit</button> </body> </html> |
To get the text of an anchor element, use the .text() method.
JS
|
1 2 3 4 5 6 |
$(document).ready(function() { $('#submit').click(function() { var text = $('a').text(); alert(text); }) }); |
HTML
|
1 2 3 4 5 6 7 8 |
<!doctype html> <html> <body> <a href="https://www.bing.com/">Click Me</a> <br><br> <button id="submit">Submit</button> </body> </html> |
2. Using JavaScript
In vanilla JavaScript, you can use the querySelector(), which will return the first anchor tag within the document. Then we can directly access the href property to get the exact value of the href attribute. The following code demonstrates this.
JS
|
1 2 3 4 |
document.getElementById('submit').onclick = function() { var href = document.querySelector('a').href; alert(href); } |
HTML
|
1 2 3 4 5 6 7 8 |
<!doctype html> <html> <body> <a href="https://www.bing.com/">Click Me</a> <br><br> <button id="submit">Submit</button> </body> </html> |
This can also be done using the getAttribute() method, which gets the value of the href attribute on the specified anchor tag.
JS
|
1 2 3 4 |
document.getElementById('submit').onclick = function() { var href = document.querySelector('a').getAttribute('href'); alert(href); } |
HTML
|
1 2 3 4 5 6 7 8 |
<!doctype html> <html> <body> <a href="https://www.bing.com/">Click Me</a> <br><br> <button id="submit">Submit</button> </body> </html> |
That’s all about getting the href value of an anchor tag in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)