Event Delegation Pattern with addEventListener and nested elements in buttons

Viewed 2502

I have a set of buttons in a parent. Each containing an SVG icon which are added programmatically. I'm attempting to listen on the parent element and then use event delegation to trigger different functionality for particular buttons, but what lands up happening is I get event targets of the contained svg's or paths rather than the buttons themselves. Is there a way to leverage event bubbling, or change the way I'm doing this to still avoid adding a ton of event handlers, and trigger the events I need? Here's some simplified code:

<div class="parent">
    // I have a whole lot of these added to the page programmatically
    <button class="some-unique-class">
        <svg> //... </svg>
    </button>
</div>

and then in my JavaScript :

document.querySelector('.parent').addEventListener('click', function(event) {

    //.. I always want to trigger events on the buttons, not
    // on the svg's and their paths.  
});

Using JQuery I'm able to do this easily, by listening on a parent element and then specifying the element, but I'd like to do this in vanilla JS.

Any help would be massively appreciated.

1 Answers
Related