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 :)
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.
Use jQuery's text function:
$(event.target).text()
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With