15

Trying to get the text of an event's target element from an unordered list

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

with code like this

$('ul').click(function() {
theEl=(event.target.text);
});

When I console log

event.target

it returns

 <li>Item 1</li>

and

event.target.text

returns undefined

I just want 'Item 1'. I know I have done this before - it must be late...thanks for any assistance :)

Charles Wyke-Smith
  • 2,479
  • 3
  • 17
  • 16

6 Answers6

29

Use jQuery's text function:

$(event.target).text()
JeffB
  • 1,887
  • 15
  • 13
9

You're confusing raw JS and jQuery.

In jQuery, you'd use $(event.target).text()

However, it's much more efficient in JavaScript: event.target.firstChild.nodeValue

EDIT: Here's a JSPerf as proof.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

The reason event.target.text is undefined is because HTMLElement does not have that method or property defined. However, jQuery does have text() which is what you were looking for. In order to access jQuery methods or properties, you need to wrap the current HTMLElement in a jquery object. This is done by passing it to jQuery, who then creates a function object with it, and the jQuery prototype which exposes the API.

jQuery(element);//in general
$(event.target).text();//for your situation
Travis J
  • 81,153
  • 41
  • 202
  • 273
2
event.target.textContent

It is javascript access too. I recommend to you execute 'Chrome' (or Firefox) javascript console with Ctrl+Shift+J. Write in your code: console.log(event) and watch the out on console. You can watch every attribute of object.

kahonmlg
  • 3,839
  • 3
  • 17
  • 21
1

Try this -> event.target.innerText

Karthik Sagar
  • 424
  • 4
  • 7
0

Solution for Vanilla JS:

event.target.options[event.target.selectedIndex].text
Jeremy Lynch
  • 6,780
  • 3
  • 52
  • 63