How to get href value using jQuery?
I'm trying to get href value using jQuery:
<html>
<head>
<title>Jquery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function(event) {
alert("As you can see, the link no longer took you to jquery.com");
var href = $('a').attr('href');
alert(href);
event.preventDefault();
});
});
</script>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
</body>
</html>
But it doesn't work. Why?
Solution 1:
You need
var href = $(this).attr('href');
Inside a jQuery click handler, the this
object refers to the element clicked, whereas in your case you're always getting the href for the first <a>
on the page. This, incidentally, is why your example works but your real code doesn't
Solution 2:
You can get current href value by this code:
$(this).attr("href");
To get href value by ID
$("#mylink").attr("href");
Solution 3:
It's worth mentioning that
$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always
Solution 4:
It works... Tested in IE8 (don't forget to allow javascript to run if you're testing the file from your computer) and chrome.
Solution 5:
if the page have one <a>
It Works,but,many <a>
,have to use var href = $(this).attr('href');