Search code examples
javascriptjqueryhtmldynamic-html

Use jquery at dynamically created element by javascript


I have made a button like this in my main.js file :

del_btn = document.createElement("button");
del_btn.className = "btn btn-light btn-sm ";
del_btn.type = "button";
del_btn.id = "delete_btn";
del_btn.innerHTML = 'X';

and put this in a <tr> which is in my index.html page. I wanted to make this alert something when the button gets clicked on. So I wrote a code that looks like this in my main.js file as well.

$("#delete_btn").click(function() {
    alert("delete button clicked!!");
});

But nothing happens when I click on the button which id is 'button'. I have no idea why this doesn't work. Does anyone know why this is not working? Any advice would be appreciated!!!


Solution

  • as per latest jquery try below

    $(document).on('click', "#delete_btn", function() {
        alert("delete button clicked!!");
    });