I’m trying to use jQuery to get the value or id of a li
element on clicking. Everything I’ve tried returns undefined
HTML
<ul id="list" class="content-ul">
<li value="0"><img src="/image0.png" /></li>
<li value="1"><img src="/image1.png" /></li>
<li value="2"><img src="/image2.png" /></li>
<li value="3"><img src="/image3.png" /></li>
</ul>
JavaScript
$( '#list li' ).click( ( event ) => {
var value = $(this).attr('value');
alert(value); // returns undefined
} );
I’ve tried using this.id
as well as $( this ).id
– undefined
I’ve tried giving the img
tag an id
and a value
– still undefined
I’ve tried giving the li
tag an id
– still again, undefined
4
Answers
The
this
context cannot be bound manually by jQuery with an arrow function. Use a regularfunction
or useevent.currentTarget
to access the element the event listener is attached to.this inside the arrow function does not refer to the DOM element that was clicked.
Why not put an "a" tag with a class and put an image inside?
Put the atrribut on the "a" tag like below:
HTML
jQuery
You can make your own data atribute, like data-id, data-name, etc.
This context cannot be bound manually by jQuery with the arrow function. Use a regular function or use event.currentTarget to access the element attached to the event listener.