JavaScript not adding eventlistener

I have the following code

var table = $('#Table');
                var lastRow = table.find('tr:last');
                var clone = lastRow.clone();
                table.append(clone);
                var button = document.createElement("input");
                button.type = "button";
                button.value = "X";
                button.name ="DeleteRow";
                button.style.width = "50%";
                button.addEventListener('click',function(){
                    DeleteRow(this);
                })
                clone.find('td:first').empty();
                clone.find('td:first').append(button);
function DeleteRow(x)
            {
                x.nearest('tr').remove();
            }

When I press the delete (x) button, nothing happens. Inspecting the code, the DeleteRow function hasn’t been added to the button, so no response. Is this a bug? Any help appreciated.

You cannot add eventlistener to elements which are not in the DOM. You first need to append the button and after add the listener…

Thanks

var table = $('#Table');
                var lastRow = table.find('tr:last');
                var clone = lastRow.clone();
                var button = document.createElement("input");
                button.type = "button";
                button.value = "X";
                button.name ="DeleteRow";
                button.style.width = "50%";
                clone.find('td:first').empty();
                clone.find('td:first').append(button);
                table.append(clone);
                button.addEventListener('click',function(){
                    DeleteRow(this);
                })

As you mentioned, adding the eventlistener after adding the button. Still not working.

Hi,

x.nearest('tr') is wrong. It should be $(x).closest('tr').remove();

The event listener was correctly added; the bug is in DeleteRow.

1 Like

Cheers @James_Hibbard @Thallius

Technically this is false.
The element has been created and exists in the DOM - it exists at the Document level. It doesn’t exist in the BODY yet, but it exists.
You cant attach an event listener to a nonexistant element, but you can attach one to an element you have floating in the Document level if you have a reference to it.

let e = document.createElement("a");
e.addEventListener("click", x => { console.log("I exist"); } )
e.click(); //Spits line into console. Still hasnt been attached.
e.innerText = "Hi";
document.getElementById("post_7").appendChild(e);
e.click(); //Still works. So does clicking on the actual element.