Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text from anchor tag

I have the following anchor tag

<a href="http://www.google.com/">Google</a> 

I know how to get the href from an anchor take:

alert($(this).attr("href")); 

But how do I get the text from the anchor tag, i.e. how do I get "Google"?

like image 822
oshirowanen Avatar asked Oct 06 '10 09:10

oshirowanen


People also ask

How can I get the text value of a clicked link?

$('#my-div a'). click(function() { var txt = $(this). text(); console. log(txt); });

How do you put text inside a tag?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.


1 Answers

Use .text() for this:

alert($(this).text()); 

If you wanted the markup (.text() removes tags and such), use .html()

alert($(this).html()); 

In this case there's no difference, if instead you had this:

<a href="http://www.google.com/">Google <span>(External)</span></a> 

Then there would be:

$(this).text() //"Google (External)" $(this).html() //"Google <span>(External)</span>" 
like image 161
Nick Craver Avatar answered Oct 12 '22 23:10

Nick Craver