3

I need to pull out some of the text from an element on my page, using jQuery, and I can't figure out how to get the piece I need.

Here's my HTML:

<a href="#" class="song">
    Soulstar
    <div>by <span class="artist">Musiq Soulchild</span></div>
</a>

I want to pull out the contents of .artist (in this case, Musiq Soulchild). First, I tried this:

var this_artist = $(this).children().text();
alert(this_artist);

That gives me by Musiq Soulchild (since this is the <a> element). So then I assumed that all I had to do was specify a selector inside the .children() method to narrow it down to the .artist class, like this:

var this_artist = $(this).children(".artist").text();
alert(this_artist);

But that gives me...nothing. I've also tried $(this).children("span").text(); and, likewise, also get back nothing.

What am I doing wrong?

4
  • 1
    Since you are using this, we need to know the context that the code is executing under. For example, is it inside an event handler? Feb 13, 2012 at 21:18
  • this is the <a> element that I'm clicking on, because this is inside of a function attached to all anchors within a particular <div>: $("#results a").live("click", function(event){...});
    – daGUY
    Feb 13, 2012 at 21:21
  • with OUT context `$('.song.artist').text(); Feb 13, 2012 at 21:21
  • 1
    FYI, .live( is depricated in favor of .on( in version 1.7.1 Feb 13, 2012 at 21:26

6 Answers 6

2

.children() only traverses the immediate children - given your markup .artist is not an immediate child. Use find() instead:

var this_artist = $(this).find('.artist').text();
2

Your selector is incorrect since .artist is not a direct child of the a element. Instead you need to use $(this).find():

var this_artist = $(this).find(".artist").text();
alert(this_artist)  

Example fiddle

1

You should use .find instead of .children. .children searches the immediate children, while .find searches descendants.

0

either

$(this).find("span.artist")

or

$("span.artist", this)

should do it... the span is a child of div, not anchor.

0

If this is an object of your link, this code returns span text:

var this_artist = $(this).find('span').text();
alert(this_artist);
0

use:

$("#results").on("click","a", function(event){
var myartist = $(this).find('.artist').text();
}); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.