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,516 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,516 Comments

@Brandon,

No problem at all. Hope this helps a bit.


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,516 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,516 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.


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,516 Comments

@Andrei,

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


Post Comment  |  Ask Ben

Recent Blog Comments
Nov 20, 2009 at 11:32 PM
Five Months Without Hungarian Notation And I'm Loving It
I've used headless camel case for years for not only ColdFusion variables, but also SQL tables and fields... pretty much everything involving code. I also subscribe to the "don't abbreviate and clea ... read »
Nov 20, 2009 at 11:00 PM
Five Months Without Hungarian Notation And I'm Loving It
@Marcel, Yeah, I always err on the side of longer but more readable variable names. As for the camel casing of CF methods and the headless camel casing of custom items, I get around this by always ... read »
Nov 20, 2009 at 10:56 PM
Five Months Without Hungarian Notation And I'm Loving It
I use the following and love it: my.namespace.MyComponents.functionMethodsOrUDF() CONSTANT_VALUES_OR_PROPERTIES One thing I always try is to CamelCaseBuiltInColdFusionFunctions() so others can tell ... read »
Nov 20, 2009 at 5:38 PM
Learning ColdFusion 8: CFImage Part I - Reading And Writing Images
Hi Ben, Great article. I've been looking around to see if ColdFusion image engine can programatically create the following "wrap around" effect: http://www.creativepro.com/article/photoshop-s-she ... read »
Nov 20, 2009 at 5:35 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
@Dave: I talked to Gert he suggested: <cfhttp method="get" url="http://{some cf website}" result="stuff" addtoken="yes" /> Note the addition of cfhttp attribute addtoken. That should persist y ... read »
Nov 20, 2009 at 5:23 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
@Todd, Ahh, gotcha, yeah that makes sense. ... read »
Nov 20, 2009 at 5:17 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
Ben, sorry if I didn't make this clear. You can make it work like that if you want, just put <cfset session.foo = 1> (and <cfset application.foo = 1>) in your OnRequestStart() and it reve ... read »