Reputation: 23574
I just trying to get the anchor text of a link.
$('a').click(function(){
alerT($(this).val());
});
<a href="#">test</a>
I have the above code, but for some reason it always returns empty.
Am i missing something?
Thank you!
Upvotes: 0
Views: 4131
Reputation: 166071
$('a').click(function(){
alert($(this).text());
});
The text
method gets any text nodes within the specified element (in this case, the anchor text). In this case html()
would work as well, but that also gets any child elements, not just text.
The val
method is used for things like input
elements, which have a value
attribute. For example:
$("input#someId").change(function() {
alert($(this).val());
});
That will alert the value entered into the input element.
Upvotes: 0
Reputation: 141935
Change val()
to text()
. You should also make that T
lowercase on alerT
, but I think that might just be a typo. You also need to make sure that your <a>
comes before your script or your script is in a document ready. One more thing is that if your href
is anything not begining with a hash, or you want to prevent the page from scrolling on click you can return false from your click event:
$('a').click(function(){
alert($(this).text());
return false;
});
Upvotes: 1