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

Posted June 30, 2009 at 10:11 AM

Tags: Javascript / DHTML, Ask Ben

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:

 Launch code in new window » Download code as text file »

  • <!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:

 Launch code in new window » Download code as text file »

  • 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.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page


You Might Also Be Interested In:



Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

Reader Comments

Jun 30, 2009 at 10:24 AM // reply »
55 Comments

Nice job, Ben!


Jun 30, 2009 at 10:28 AM // reply »
6,371 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"
. . . });
}


Jun 30, 2009 at 11:17 AM // reply »
39 Comments

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!


Jun 30, 2009 at 11:18 AM // reply »
6,371 Comments

@Brandon,

No problem at all. Hope this helps a bit.


Paul S
Jun 30, 2009 at 12:01 PM // reply »
1 Comments

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.


Jun 30, 2009 at 2:11 PM // reply »
6,371 Comments

@Paul,

Take a look at this:

http://www.bennadel.com/blog/1624-Ask-Ben-Overriding-Core-jQuery-Methods.htm


Jun 30, 2009 at 7:54 PM // reply »
15 Comments

well done Ben. Pretty nifty


Pat
Jul 22, 2009 at 11:44 AM // reply »
1 Comments

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 !


Jul 27, 2009 at 1:37 PM // reply »
6,371 Comments

@Pat,

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


Andrei
Aug 19, 2009 at 10:16 AM // reply »
1 Comments

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


Sep 6, 2009 at 1:55 PM // reply »
6,371 Comments

@Andrei,

Yeah, it will only work when you use the remove() jQuery methods.


Post Comment  |  Ask Ben

Recent Blog Comments
Jill
Nov 7, 2009 at 11:40 AM
How To Unformat Your Code (Like A Pro)
Derek, I think you might be right - sweet! Thanks for the link :) ... read »
Nov 7, 2009 at 11:25 AM
How To Unformat Your Code (Like A Pro)
I think it would be way easier to just use this http://www.logichammer.com/html-formatter/ He just released v3 and it rocks. ... read »
Jill
Nov 7, 2009 at 7:58 AM
How To Unformat Your Code (Like A Pro)
LMAO - this was pretty funny! I have to admit - I also love to reformat code so I can read it. My boss used to tell me to leave my OCD at home. Now I don't feel so bad after reading everyone else' ... read »
Nov 6, 2009 at 10:10 PM
How To Unformat Your Code (Like A Pro)
The timing of this post is just uncanny. I spent the last 15-20 minutes manually un-formatting my "Ben Nadel" style code within a CFC of mine. I was really digging the readability a few weeks ago, bu ... read »
Roe
Nov 6, 2009 at 5:11 PM
Passing Arrays By Reference In ColdFusion - SWEEET!
ArraySort also reorders the results of these java obj's ... read »
Nov 6, 2009 at 4:53 PM
How To Unformat Your Code (Like A Pro)
I tried to go *back* the other way. Adding formatting is actually a much more complicated problem than removing formatting. Anyway, here is what I could put together with a minimal amount of time: ... read »
Asaf
Nov 6, 2009 at 2:35 PM
ColdFusion GetPageContext() Massive Exploration
Hi, I actually found this post useful. I recently acquired a SSL certificate for my website and when I switched over to HTTPS Internet Explorer would throw an error when trying to download a dynamic ... read »
Nov 6, 2009 at 2:19 PM
How To Unformat Your Code (Like A Pro)
@Chuck, @Nathan, Well, now I feel like it's a challenge.... I accept. ... read »