Advertisements
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
Been poking at this for hours, all I get for the alert is undefined
>Solution :
this inside the arrow function does not refer to the DOM element that was clicked.
$( '#list li' ).click(function() {
var value = $(this).attr('value');
alert(value); // returns undefined
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>