Cloning element event listeners

I know that the cloneNode() method does NOT copy event listeners, but I was wondering if there was another native (vanilla JS) method that does so?

for example. I created DOM elements for a TABLE, A TR, and a TD. each TD is supposed to have an onClick event attached. Currently, am having to fully create ALL the cells in each row and all the rows in the table then go back and looping trough all the newly created TDs to attach the even listenteners. I feel it would be far more graceful if it were possible to create a prototype TD , to which I would attache the onCLick listener ONCE, and clone that into a prototype TR and finally clone those into the TABLE element. Is this possible at all?

Rather than attaching an event handler for each element, it would be more efficient to delegate to a parent element. This would also work for any dynamically inserted elements.

If you were using jQuery, it’d be as simple as doing something like this:

$('table#mytableid').on('click', 'td', function() {
  // handler code
});

but you can find some vanilla JS that’ll do the job here: http://bdadam.com/blog/plain-javascript-event-delegation.html

am sorry, am still a little lost…
since I a trying NOT to use jQuery I followed the link to the vanilla JS solution. And I get that the event is being attached to the parent container. bUt what I dint see is:

  1. How are the action actually being called by a click to the child element ( nit picking, I just understand the mechanism)
  2. Since you are looping through all the ‘possible target’ it really isn’t that different than my current method of looping though all the ‘clickable’ elements
  3. also, I was concerned because the example is attaching an action to an element that was created by the markup where I am creating elements in the DOM with JS

Perhaps this is enough of a code sample to show you how to work out what was clicked on (there is no looping involved at all)

... addEventListener('click', function(e) {clickedElement= e.target; ....

Ah HA! moment. Thanks guys!!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.