Search code examples
javascriptstoppropagation

how to using "stopPropagation" on parent dom?


In pic above,parent dom node has its event and child nodes have too.

I can use stopPropagation in Child to prevent bubbling.

but in that case, if have too many children, too much stopPropagation should writed. Is there a function using on parent node can stop child bubble ?


Solution

  • It sounds like you want to avoid doing the work the parent's event handler does if the event passed through a particular kind of child element. In that case, in your parent event handler, you can use event.target to figure out whether the event passed through a matching child.

    In semi-pseudo-code:

    theParentElement.addEventListener("the-event", function(e) {
        for (var node = e.target; node && node != this; node = node.parentNode) {
            if (isChildWeWantToFilterOut(node)) {
                return;
            }
        }
    
        // parent handler logic that you only want to run when the
        // event didn't pass through a relevant child
    }, false);