开发者

Get text from anchor tag

开发者 https://www.devze.com 2023-01-19 02:18 出处:网络
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:

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"?


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>"


On using the .text() as mentioned, I got the text of all the anchor tags combined in my code:

HTML:

<div class="col-sm-2 jumbotron jumbotronUserRaces list-group list-group-
userRaces" id="listGroupUserRaces">
                <a href="" class="list-group-item active">First item</a>
                <a href="" class="list-group-item">Second item</a>
                <a href="" class="list-group-item">Third item</a>
            </div> 

JS:

$("#listGroupUserRaces").click(function () {
   alert($(this).text());
});

OUTPUT:

  • First item
  • Second item
  • Third item
0

精彩评论

暂无评论...
验证码 换一张
取 消