The W3C DOM specifications have introduced some interesting DOM events which trigger when some modifications have been made to the structure of the document. One of this events is DOMNodeRemoved
, which fires when an element node is removed. We can use this event to trigger an action with jQuery when an element is removed from the page.
We have this simple structure:
<ul id="test"> <li>A</li> <li>B</li> <li>C</li> <li>D</li> <li>E</li> </ul>
By clicking on each list item we remove the current node:
$('li', '#test').click(function() { $(this).remove(); });
Now we use the DOMNodeRemoved
event:
$('#test').bind('DOMNodeRemoved', function(e) { var element = e.target; var text = element.tagName + ': ' + element.firstChild.nodeValue + ' removed '; alert(text); });
The target
property of the event object points to the current element that has been removed. You can see the demo below.