Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding event listener on a dom element inside template tag

Suppose I have button inside a template

<template id="persons">
     <tr>
         <td></td>
         <td></td>
         <td><button type="button" id="delete" class="btn btn-danger">Delete</button></td>
     </tr>
</template>

Now im trying to add an event listener to the button by

this.oBtnDel = document.getElementById('delete');

this.oBtnDel.addEventListener("click", somefunc);

however im getting an error saying

Cannot read property 'addEventListener' of null

how can i fix this?

like image 818
Beginner Avatar asked Oct 20 '25 11:10

Beginner


1 Answers

Items in templates are not part of the regular DOM. They will not be there when you are binding the event listener. You will also have a problem with id="delete" if you have more than one as Ids must be unique.

What you need to do is use event delegation, and I will use a data attribute to identify the button.

Template

<template id="persons">
     <tr>
         <td></td>
         <td></td>
         <td><button type="button" data-action="delete" data-objectid="id to delete" class="btn btn-danger">Delete</button></td>
     </tr>
</template>

Javascript

//Bind the event to the parent table say it has an id of parentTable
this.oTable= document.getElementById('parentTable');    
this.oTable.addEventListener("click", function(event){
   //check the delete button was clicked
   if(event.target.dataset.action === "delete")
   {
       //Logic for delete goes here
       var idToDelete = event.target.dataset.objectid;
       /*Rest of your logic*/
   }
});

NOTE the code above is untested. If it doesn't work, you should be able to fill in the gaps with the links provided.

Further reading on event delegation: https://davidwalsh.name/event-delegate

like image 136
Jon P Avatar answered Oct 23 '25 03:10

Jon P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!