Benjamin Anderson
Benjamin Anderson

Reputation: 367

Selecting the text out of an <a> element with jQuery?

I'm trying to grab the text section of this html:

<li class="location"><a href="#">Some Text</a></li>

with this jQuery:

$('.location').off('click').click(function() {
alert($(this).children('a')[0].text());
}

So that my alert displays "Some Text". I'm just not sure why it's not working.

Upvotes: 1

Views: 55

Answers (2)

user3014162
user3014162

Reputation: 1

Try

$('.location').off('click').click(function () {
alert($(this).children('a').html());

});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388406

The .text() method is provided by jQuery wrapper element, children('a')[0] gives an DOM element which does not have that method.

Using the getter format of text() returns the text content of the first element in the given set which is what you are looking for

$('.location').off('click').click(function () {
    alert($(this).children('a').text());
});

Upvotes: 4

Related Questions