Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to get text of target

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 :)

like image 636
Charles Wyke-Smith Avatar asked Feb 06 '13 02:02

Charles Wyke-Smith


4 Answers

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.

like image 20
Niet the Dark Absol Avatar answered Nov 04 '22 01:11

Niet the Dark Absol


Use jQuery's text function:

$(event.target).text()
like image 144
JeffB Avatar answered Nov 04 '22 03:11

JeffB


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
like image 2
Travis J Avatar answered Nov 04 '22 03:11

Travis J


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.

like image 2
kahonmlg Avatar answered Nov 04 '22 02:11

kahonmlg