Find closest element on click with jQuery

Jens Törnell picture Jens Törnell · Jun 1, 2017 · Viewed 7.7k times · Source

I trigger a function by click on a nested element. To prevent bubbling I could use e.stopPropagation();.

If stop propagation, other scripts have trouble because they rely on bubbling on these elements. Is there another way around it? Some kind of if statement?

html

<div class="nested-element">
  <div class="nested-element">
    content
  </div>
  content
</div>

The nesting is in real life unlimited.

jquery

$('.selector').on('click', '.nested-element', function(e) {
    //e.stopPropagation();
    console.log($(this));
});

The above will output the root parent first and then move closer to the closest element. I only want to get the closest element.

Answer

charlietfl picture charlietfl · Jun 1, 2017

You can check the target and if target is in a descendant instance of the class do nothing

$(document).on('click', '.nested-element', function(e) {
   if(!$(e.target).closest('.nested-element').not(this).length){
     console.log('nested-element clicked =', this.id);
   }else{      
     console.log('Ignore parent event')
   }     
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent" class="nested-element">
  <div id="child" class="nested-element">
    child content
  </div>
  parent content
</div>