Reputation: 2507
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 :)
Upvotes: 16
Views: 38830
Reputation: 7230
Solution for Vanilla JS:
event.target.options[event.target.selectedIndex].text
Upvotes: 0
Reputation: 4049
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.
Upvotes: 2
Reputation: 82357
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
Upvotes: 2
Reputation: 324840
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.
Upvotes: 10