Jason Gelinas Jason Gelinas - 6 months ago 9
Javascript Question

Removing a dynamically created li from ul

I'm using jquery to add and remove bullets on the fly after the DOM is loaded.

Here's the code to add a bullet which works fine:

// add bullet
$('#linkedEventList ul').append('<li id=' + datum._id + '>' + datum.headline + ' <a href=javascript:; title=delete onclick=remove(this) class=itemDelete>(x)</a> <a href=/events/' + datum._id + '>(open)</a></li>');


Now here's the code to remove the clicked bullet, which works fine in Firefox, but does not work right in Chrome. In Chrome, the hyperlink is removed and not the parent or li.

// remove bullet
//$(link).closest('li').remove();
$(link).parent().remove();


Either method above works fine in FireFox, but neither works in Chrome. Any ideas on the solution?

jsfiddle: http://jsfiddle.net/jjgelinas77/CsAJn/14/

Answer

I used a combination of the answers provided.

I removed the onclick in the li, and instead referenced the class being clicked and combined that with 'this' as per below.

$('#linkedEventList').on('click', '.itemDelete', function(){
$(this).parent().remove();
});

Here's the jsfiddle that works in both FireFox and Chrome: http://jsfiddle.net/jjgelinas77/CsAJn/27/

Comments