Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JQuery – $( this ).attr('value') returns undefined

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$( '#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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading