$('.parent').on('click', function(e) { if (e.target.matches('.inside')) { console.log('inside'); } else { console.log('title'); } });
.parent { background: lightgreen; } .inside { background: silver; } .title { background: gold; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='parent'> <div class='inside'> <div class='title'>lorem</div> </div> <br> </div>
Click on inside
and you'll get title
in console.
How to get inside
regardles a title
is inside or not?
You need to check if the target
has a parent .inside
:-
$('.parent').on('click', function(e) { if ($(e.target).parents('.inside').length) { console.log('inside'); } else { console.log('title'); } });
.parent { background: lightgreen; } .inside { background: silver; } .title { background: gold; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='parent'> <div class='inside'> <div class='title'>lorem</div> </div> <br> </div>
Okay take a look at this and see if it works for you?
https://codepen.io/jamie-endeavour/pen/GPjzRq?editors=1011
$('.parent').on('click', function(e) {
var $target = $(e.target);
if ($target.hasClass('inside') || $target.parent().hasClass('inside')) {
console.log('inside');
} else {
console.log('not inside');
}
});
I am checking if the user has clicked on the element with the 'inside' class or if the child element belongs to the 'inside' element.
Hope this helps?
Please note that HTML works in layer so if title is going to be inside "inside", you can just target title for click as inside is always "inside" it.
$('.title').on('click', function(e){ console.log('inside'); });
.parent{ background:lightgreen; } .inside{ background:silver; } .title{ background:gold; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='parent'> <div class='inside'> <div class='title'>lorem</div> </div> <br> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.