13

Possible Duplicate:
Select inner text (jQuery)

I have a span:

<span class="test"> target_string </span>

And the event, that is fired on click on any element of the page.

$('body').click(function(event){
  if ($(event.target).attr('class') == 'test'){
    alert(???);
  }
}

How can I obtain target_string value?

Community
  • 1
  • 1
mol
  • 2,607
  • 4
  • 21
  • 40

4 Answers4

29

Use $(event.target).text() to get the text.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
3

Possibly more efficient to delegate from the body:

$('body').on('click', '.test', function(event){
    alert($(this).text())
});
Simon Smith
  • 8,024
  • 2
  • 30
  • 40
1

Try below,

$('body').click(function(event){
  var $targ = $(event.target);
  if ($targ.hasClass('test')){
    alert($targ.text());
  }
}
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
0

Not sure if you plan to work with other elements inside that event handler besides those with a class of test, but this may be more concise:

$('.test').click(function(event){
    alert($(this).text());
});
Brian
  • 325
  • 2
  • 10