Martin
Martin

Reputation: 11336

closest in jQuery not working

I try to click on .dropzone class through jQuery when users click on .dropzone-upload-btn element. I have this code but it is not doing anything. Any idea why?

<div class="dropzone-wrapper">
  <div class="dropzone"></div>
  <div class="dropzone-upload-btn"></div>
</div>

And this is the jQuery code (simplified)

$('.dropzone-upload-btn').on("click", function() {
  return $(this).closest('.dropzone').click();
});

Upvotes: 1

Views: 133

Answers (1)

Ian
Ian

Reputation: 50905

closest looks at the matched element and its ancestors. You probably want siblings:

$('.dropzone-upload-btn').on("click", function() {
    return $(this).siblings('.dropzone').click();
});

References:

Of course, if you're 100% sure the .dropzone element will come immediately before the .dropzone-upload-btn element, then you can use prev or prevAll:

$('.dropzone-upload-btn').on("click", function() {
    return $(this).prev('.dropzone').click();
});

References:

prevAll can be used if you know the target element will come before the matched one, but not necessarily immediately before. prev will only look at the first immediate previous sibling.

The difference between prevAll and siblings is that siblings looks at siblings before and after the matched element, while prevAll looks only at the siblings before it.

Upvotes: 4

Related Questions