$('.myclass').click(() => {
let myvar = this;
console.log(this.tagName);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<li><button class="myclass">click me</button></li>
Output in the console is undefined, but I expected button? I need a data-* attribute from that button (you're looking at reduced/minimalized code), but I cannot even grab the element via this - why not?
Inside the click handler
thisreferes to window object. Sothis.tagNameis undefined. To access that element you should use event's target.If you want to access data attribute then you can wrap
e.targetwith jQuery and use data function for same.The javascript code to get data-id is.