Seppia Anthony Seppia Anthony - 1 year ago 89
Javascript Question

jQuery click method on nested classes

Starting from the snippet:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body>
<ul>
<li><a class="parentClass" href="#">Parent</a></li>
</ul>

<script>
jQuery(document).ready(function($){

$('.parentClass').append("<span class='childClass'> || Child</span>");

$('.parentClass').click(function(e){
alert('parent');
});

$('.childClass').click(function(e){
//$('.childClass').removeClass('parentClass');
alert('child');
});
});
</script>
</body>
</html>


If I click on "Parent" I can view the
alert('parent')
only, but if I click on "Child" I will fire not only
alert('child')
but also
alert('parent')
.
I tried to insert
$('.childClass').removeClass('parentClass');
but it doesn't work. I can't figure out how to avoid to launch the parent from child, without modify the nested classes inside the anchor...is it possible?

Answer Source

Events bubble, you can stop the propagation

jQuery(document).ready(function($) {

    $('.parentClass').append("<span class='childClass'> || Child</span>");

    $('.parentClass').click(function(e) {
        alert('parent');
    });

    $('.childClass').click(function(e) {
        e.stopPropagation();
        alert('child');
    });
});

FIDDLE

or make sure the parent was actually the target

jQuery(document).ready(function($) {

    $('.parentClass').append("<span class='childClass'> || Child</span>");

    $('.parentClass').click(function(e) {
        if ( this === e.target ) {
            alert('parent');
        }
    });

    $('.childClass').click(function() {
        alert('child');
    });
});

FIDDLE