javascript - trick/guideline to remove DOM element

remove an element is not as simple as calling parent.RemoveChild, housekeeping include 

 

  1. remove element should clean the handler that is associated with the element, otherwise, IE will leak memory should the function reference an external DOM element
  2. remove the data associated with the element
  3. remove should happen on the element (the parent) and all its descendant

and there is a caveat on IE, where most browsers will reclaim the memory happily, IE does not reclaim the memory that is occupied by the removed elements until the page is left.  


I am giving a pseudo-code as follow to show you you would normally write the remove function if  you ever need to do so. 


/**
* @Comment: this shows you how to remove DOM element from the tree, it worth the discussion because  
*   1. remove element should clean the handler that is associated with the element, otherwise, IE will leak memory should the function reference an external DOM element
*   2. remove the data associated with the element
*   3. remove should happen on the element (the parent) and all its descendant
* one caveat abou the remove, after the removal of the element, browsers may have different strategy to reclaim the memory it used, IE is an exception where it fail to reclaim 
* the memory until the page is finally left. 
* 
* so, for IE,an additional step is to set the outerHTML = "" (a trick) , which will wipe out elment from IE's memory more completely than simply doing removing child. 
*
* NOTE: this code shows example, and is not supposed to be useful without context.
*/
function remove() {
  // go through all descendants and the element to be removed.
  jQuery("*", this).add([this]).each(function () {
    // remove all bound events 
    jQuery.event.remove(this);
    // remove attached data
    jQuery.removeData(this);
  });
  // remove the element (if it 's in the DOM)
 
  if (this.parentNode) {
    this.parentNode.removeChild(this);

  // if it is IE, you will need to set the outerHTML as well
    if (typeof this.outerHTML !== "undefined")
      this.outerHTML = "";
  
  }
}
 

你可能感兴趣的:(JavaScript)