DOM removal and events

Let’s try something… go to a page with jQuery enabled (such as this one), and run the following code in your Javascript debugger console (such as Firebug):

var button =
  $('<button>Click me</button>')
  .click(function(){alert('Clicked!')})
  .appendTo('body')

In case you were wondering, this creates a brand new button, causes it to display a “Clicked!” message box when it’s clicked, and appends it to the document you are viewing.

Click on the button that just appeared : the message box appears. Not very surprising.

Now, run the following code on the same page :

$('body').html('');
button.appendTo('body')

As expected, everything on the page, including the button, disappears. However, the button is still referenced by the button variable, so it sticks around and we can append it back to the document. And indeed, it does appear on the page.

Click on the button again. This time, no message box appears.

I honestly have no idea why.

4 Responses to “DOM removal and events”


  1. adam j. sontag - January 8, 2010 at 1:19 am - Reply

    because removing an element from the dom does NOT destroy it. it merely removes the element from the dom. the reference to a button element does not go away just because the body is emptied.

    this is useful for working with elements “off of the dom” which will prevent additional reflows and help with performance, for instance.

    var foo = $(“#foo”).remove(), width = foo.width();

    foo.children(“div”).addClass(“hello”).css(“with”,width);

    foo.insertBefore(“#bar”);

  2. Emptying the body doesn’t destroy the reference to the element you created. Imagine creating a variable with a string. Would you expect that to suddenly disappear if you emptied the body? In the same way, the element you created a reference for (in this case button), still exists, with or without the page.

  3. Victor Nicollet - January 8, 2010 at 11:19 am - Reply

    @Adam and Tom: thank you for your answers. I already know why the element itself sticks around and can be inserted into the DOM again: JS is a garbage-collected language, and the DOM elements stay alive as long as they are referenced.

    What I don’t know is why the click event I registered on the object disappears.

  1. 1 That DOM removal thing, again at Nicollet.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



1150 feed subscribers
(readers who polled a feed this week)