Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at NCDevCon 2011 (Raleigh, NC) with: Jaana Gilbert and Brenda Priest

Ask Ben: Detecting When DOM Elements Have Been Removed With jQuery

By Ben Nadel on

I know that jQuery is great for event management, but I was wondering if you have come across a way to detect if a DOM element (say a row in a table) was removed? I have a table and I want to run an ajax request every time a tr was removed, but there are several ways that the tr could be removed.

If you look at the W3C, there is actually an event that gets triggered when a DOM element is removed from a document sub-tree:

DOMNodeRemoved: Fires when a node has been removed from a DOM-tree.

This DOM event will bubble up the document tree with the removed node as its target. But of course, even though this is a standard in the W3C, it's not fully supported in the various browsers. And, somewhat to be expected, from my brief testing, the one browser that I have that doesn't support this event type is Internet Explorer. However, if we are going to be using jQuery to perform our DOM mutations, we can actually simulate this event if the current browser is IE:

 
 
 
 
 
 
 
 
 
 

Before we look at the IE hack, let's just take a look at our standard test code:

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • <html>
  • <head>
  • <title>DOM Modification Event</title>
  • <script type="text/javascript" src="jquery-1.3.2.js"></script>
  • <script type="text/javascript">
  •  
  • $(function(){
  •  
  • // Bind link handlers to remove links.
  • $( "p#children a" )
  • .attr( "href", "javascript:void( 0 )" )
  • .dblclick(
  • function( objEvent ){
  • // Remove link.
  • $( this ).remove();
  •  
  • // Cancel click event.
  • return( false );
  • }
  • )
  • ;
  •  
  • // Bind link hanlders to remove parent.
  • $( "p#nested a" )
  • .attr( "href", "javascript:void( 0 )" )
  • .dblclick(
  • function( objEvent ){
  • // Remove parent.
  • $( this.parentNode ).remove();
  •  
  • // Cancel click event.
  • return( false );
  • }
  • )
  • ;
  •  
  • // Listen to the body for any DOM modifications in
  • // which a DOM element is removed.
  • $( "body" ).bind(
  • "DOMNodeRemoved",
  • function( objEvent ){
  • // Append event to log display.
  • $( "#event-log" ).append(
  • "<li>" +
  • "Node removed: " +
  • $( objEvent.target ).text() +
  • "</li>"
  • );
  • }
  • );
  •  
  • });
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <h1>
  • DOM Modification Event Demo
  • </h1>
  •  
  • <p id="children">
  • <a>Remove Me 1</a>
  • <a>Remove Me 2</a>
  • <a>Remove Me 3</a>
  • <a>Remove Me 4</a>
  • </p>
  •  
  • <p id="nested">
  • Child Action: <a>Remove my parent</a>
  • </p>
  •  
  • <h2>
  • Event Log
  • </h2>
  •  
  • <ul id="event-log" />
  •  
  • </body>
  • </html>

As you can see, in the first event binding, we are telling the double-click event to remove the given link from the document. Then, in the second event binding, we are telling the double-click event to remove the given parent element (of the clicked link) from the document. So far, this is just standard jQuery code; it's the third event binding that gets interesting. Here, we are binding an event listener to the BODY tag to listen for the "DOMNodeRemoved" event. Since the DOMNodeRemoved event bubbles up through the parent DOM, the body tag will be able to listen for any of the elements being removed in its tree.

Once we have this event listener bound to the BODY, we are catching the events and outputting the text() of the target node (the one being removed) for debugging.

Now, the DOMNodeRemoved event fires implicitly for all the Mozilla / Safari based browsers (it seems). But, like I said before, IE does not want to cooperate. As such, we have to do a little fenagling and actually fire the DOMNodeRemoved event explicitly. While irritating, this is actually easy so long as we are using jQuery to do all of our DOM mutation (which I assume most of us are by now). All we have to do is modify the remove() function in the jQuery library:

  • remove: function( selector ) {
  • if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
  • // Prevent memory leaks
  • jQuery( "*", this ).add([this]).each(function(){
  • jQuery.event.remove(this);
  • jQuery.removeData(this);
  • });
  •  
  • // -------------------------------------------- //
  • // If this is IE, then manually trigger the DOM
  • // node removed event on the given element.
  • if (jQuery.browser.msie){
  • jQuery( this ).each(function(){
  • jQuery( this ).trigger({
  • type: "DOMNodeRemoved"
  • });
  • });
  • }
  • // -------------------------------------------- //
  •  
  • if (this.parentNode)
  • this.parentNode.removeChild( this );
  • }
  • }

As you can see, I've added just a few lines of logic to jQuery's remove() method which states that if the current browser is MSIE, then manually trigger the "DOMNodeRemoved" event on the target element. Since jQuery automatically bubbles events through the DOM, this event will now bubble up to the BODY tag at which point it will trigger the DOMNodeRemoved event listener that we bound earlier. And, since we triggered the event on the target element, the Target property of the event object will be the same in IE as it is in the Mozilla browsers.

I have not tested this a whole lot, but this solution seems to work well in Firefox, Chrome, Safari, and Internet Explorer. I hope this helps or at least points you in the right direction.




Reader Comments

@Hal,

Thanks! It was an interesting question that was asked.

Actually, looking at the code, the each() and the trigger() are redundant (as trigger will apply to each element in the set). The code can be reduced to:

if (jQuery.browser.msie){
. . . jQuery( this ).trigger({
. . . . . . type: "DOMNodeRemoved"
. . . });
}

Reply to this Comment

That is pretty darn awesome! I definitely need to spend some more time over at the w3c. Of course, so do the guys at Microsoft...

Thanks so much for taking the time on this one!

Reply to this Comment

is there a way to overload the included remove() function in jquery? possibly a seperate js file? for example we are using the min version and it would be cool to not have to add this in each time we upgraded to a new version that has come out?

thanks,
Paul S.

Reply to this Comment

Hi,

I'm trying to do the same thing with the DOMAttrModified and the attr jquery function.
But in IE i can't get the "attrName" and "newValue".

Do you have any ideas ?

Thanks !

Reply to this Comment

@Pat,

You'd probably have to do the same thing that we did with the remove() method, but with the attr() and removeAttr() methods.

Reply to this Comment

Unfortunately it's does not help if changing innerHTML or innerText or using DOM methods.
Do you have any ideas ?

Reply to this Comment

It's a good start but the problem is this:

1. Element "A" is a child of "P"
2. I append element "A" to another element "B"
3. The browser's DOM automatically removes "A" from "B" (since an element cannot be a child of two elements)
4. I never receive a remove event

Reply to this Comment

I have different type of problem. I am creating a Javascript class using Jquery. One function creates DOM elements and append to particular divID. I presume that once appended it is available in the document. But when I try to access the new element appended from another function it gives null. I have created 2 div of class name ".widget" with first function. with the second function I want to iterate say $('.widget').each(). But there is no element . Why is this problem arises.

Reply to this Comment

Since the DOMNodeRemoved event is supported in IE9, I think it is a good idea to change

if (jQuery.browser.msie)

into

if ($.browser.msie && $.browser.version < 9)

to ensure that the event does not fire twice in IE9

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.