Alex Pham Alex Pham - 3 years ago 122
Javascript Question

how to remove list item with dynimically created button in javascript

I created a button in javascript attaching it to the list item, but I can't seem to remove it with the same button created. here is what I started with. Any help would be great. Thanks.

//creating remove button works fine, problem is deleting the list item

var button = document.createElement('button');
var txt = document.createTextNode('\u00D7');
button.id = "close";
button.appendChild(txt);
item.appendChild(button);
list.insertBefore(item, list.childNodes[0]);
}

// this is what I came up with but it does not work.
// I do get an error "Cannot set property 'onclick' of null."

var close = document.getElementById('close')
close.onclick = function() {
var div = this.parentElement;
div.style.display = 'none';
}

Answer Source

Try the fiddle https://jsfiddle.net/7594zay3/1/ The addEventListener should be part of the addItem method.

 list.insertBefore(item, list.childNodes[0]);
 var close = document.getElementById('close')
 close.addEventListener("click", function(){
 var div = this.parentElement;
 div.style.display = 'none';
 });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download