Using CSS, it's very easy to attach a certain style for all elements sharing the same class. I would like to do something similar, but for DOM event handlers rather than styles. E.g. I'd like all elements with class my-class
will have the same handler for a click event.
I know this can be done easily using a selector after the page is loaded, e.g. in jQuery:
$('.my-class').click(function() {alert('clicked');})
but I wonder if this can be achieved using DOM event delegation. The canonical answer suggests that delegation can be used to propagate an event from a child node to its parent (or ancestor, in general). Is it possible to define a handler on a single node with my-class
, and have all the other elements with my-class
delegate to it, even if they aren't descendents?