Search code examples
javascriptjqueryclickthis

Javascript: this is undefined inside jquery click function


$('.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?


Solution

  • Inside the click handler this referes to window object. So this.tagName is undefined. To access that element you should use event's target.

    $('.myclass').click((e) => {
      console.log(e.target.tagName);
    })
    

    If you want to access data attribute then you can wrap e.target with jQuery and use data function for same.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <li><button class="myclass" data-id="1">click me</button></li>
    

    The javascript code to get data-id is.

    $('.myclass').click((e) => {
      console.log($(e.target).data('id'));
    })