Say you have this html:
<div class="parent">
<a href="#" class="child"></a>
<span>other elements</span>
</div>
<div class="parent">
<a href="#" class="child"></a>
<span>other elements</span>
</div>
the child have a click event listener:
$('body').on( 'click', '.child', doSomething );
How can I make the click be triggered if any part of the parent element is clicked? I tried something like this, but it doesn't work. The doSomething function isn't getting triggered.
$('.parent').each( function() {
$(this).on( 'click', function( e ){
$(this).find('.child').triggerHandler('click');
e.preventDefault();
} );
});
You do not need .each()
at all here.
You can try the following way:
$('.parent').on('click', function(e){
$(this).find('.child').get(0).click();
e.preventDefault();
});
$('body').on('click', '.child', doSomething);
function doSomething(e){
console.log('Child of ' +$(e.target).parent().index() +' parent tiggered');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<a href="#" class="child"></a>
<span>other elements</span>
</div>
<div class="parent">
<a href="#" class="child"></a>
<span>other elements</span>
</div>