Search code examples
javascriptjqueryjquery-selectorsthis

$(this) is selecting window object instead of clicked element jquery


I have a really strange issue. I simply want to select a clicked element. I did this a lot of times and it always worked but this time, the jQuery $(this) selector doesn't select the clicked element, it selects the window object. Please let me know, if you have an idea, what could be the reason for this. I am using jQuery 2.1.4 and Twitters Bootstrap 3.3.5

HTML:

<a class="btn btn-danger btn-xs delete-file"><i class="fa fa-trash" aria-hidden="true"></i> Löschen</a>

jQuery:

$(document).ready( () => {
   $('.delete-file').on('click', () => {
      let element = $(this);
      console.log(element);
    });
});

Console-Output:

n.fn.init [Window]

instead of:

n.fn.init [a.btn.btn-danger.btn-xs.delete-file]

Thank you in advance!


Solution

  • It's because you're using an arrow function. The scope of the contents of this function do not change as per a standard function definition. For this to work you'll need to change the logic:

    $(document).ready(() => {
      $('.delete-file').on('click', function() {
        let element = $(this);
        console.log(element);
      });
    });
    

    Alternatively you could keep the arrow function and retrieve a reference to the clicked element through the target property of the event that's raised:

    $(document).ready( () => {
      $('.delete-file').on('click', e => {
        let element = $(e.target);
        console.log(element);
      });
    });