I'm trying to insert html data dynamically to a table that is dynamically created, but when i try to attach an addEventListner for the button that is dynamically created the event is not firing. Solution would be really appreciated.

Asked by Sanyam Khatri about 2 years ago



<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CRUD OPERATIONS</title> <style> table , th , td { border: 1px solid black; border-spacing: 5px; table-layout: auto; width: auto; }
        overflow: auto;
</head> <body> <div > <table class = "puthere"> <tr class="dynamic"> <th>BOOKS</th> <th class = "books">PRICE</th> <th > <button class="create" > CREATE</button> </th> </tr> <tr class = "update-delete dynamic"> <td><input type="text" class="v1"></td> <td><input type="text" class="v2"></td> <td> <button class = "active-update" data-set=".active-update"> UPDATE </button></td> <td> <button > ❌ </button></td> </tr> </table> </div> <script src="script.js"></script> </body> </html>


const put = document.querySelector(".puthere"); const v1 = document.querySelector(".v1"); const v2 = document.querySelector(".v2"); const create = document.querySelector(".create"); const updateDelete = document.querySelector(".update-delete"); const update = document.querySelectorAll(".active-update"); const dynamic = document.querySelector(".dynamic");


const operations = function (v1, v2) { const html = ` <tr class = "update-delete">

<td> <input type="${v1}"></td> <td ><input type="${v2}"></td> <td> <button class = "active-update" data-set=".active-update"> UPDATE</button></td> <td> <button > ❌ </button></td>

put.insertAdjacentHTML("beforeend", html);



create.addEventListener("click", function (e) { operations(v1.value, v2.value); });

updateDelete.addEventListener("click", function (e) { if( && == '.active-update'){ console.log('click ') } });

1 Answer


    Select the button by it's class name and add an event listener.

    document.querySelector('.create').addEventListener("click", function (e) { operations(v1.value, v2.value); });

    document.querySelector('.update-delete').addEventListener("click", function (e) { if( && == '.active-update'){ console.log('click ') } });

    This will work.


    Kirubha Vignesh


Your answer