`

javascript - trick to clone an element

阅读更多

it should worth an article specifically for this topic to clone some elements, most of the cases should be fairly straight forward to clone some elements. 

 

However, the complication comes with the internet explorer, where you have the behaviors that, when they occurs in conjuction, result in a very frustrating scenario for handling cloning. 

 

 

 

first, when cloning an element, Internet explorer copies over all event handlers onto the cloned element. Additionally, any custom expandos attached to the cloning are also carried over.

 

 

while you cannot just clone the element in IE and then remove the attached events or expandos, because ironically doing so will remove the event handlers and others from the original elements as well. 

 

the solution just clone the element, inject it into another element, then read the innerHTML of the element - and convert that back into a DOM node.

 

while it sounds all good, but is not yet the whole picture, nasty problems still exist in IE, where 

 

  1. innerHTML /outerHTML (for that matter) of an elemnt does not always relfect to the correct status, if the name attributes of input elements are changed dynamically - the new value isn't represented in the innerHTML.
  2. XML DOM elemnts does not have innerHTML (we need to look up what is the definition of innerHTML)
so the ultimate solution,put into word, would be 

Instead of a quick call tocloneNode it is, instead, serialized by innerHTML, extracted again as a DOM node, and then monkeypatched for any particular attributes that didn't carry over.

How much monkeying you want to do with the attributes is really up to you.


SO much for/of the talk, let 's take a look a portion of the jQuery's code on the node cloning. 


/**
*@Comment : this code is not supposed to be used directly, instead it is written here to show you 
* the algorithm to do cloning in libraries such as jQuery. In real use case, you may directly use the jQuery libraries
*/
function clone() {
  var ret = this.map(function () {
    if (!jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this)) {
      var clone = this.cloneNode(true),
      container = document.createElement("div");
      container.appendChild(clone);
      return jQuery.clean([container.innerHTML])[0];
    } else {
      return this.cloneNode(true);
    }
  });

  var clone = ret.find("*").andSelf().each(function () {
    if (this[expando] !== undefined) this[expando] = null;
  });

  return ret;
}
 

Note that the above code uses jQuery's jQuery.clean method which converts an HTML string into a
DOM structure (which was discussed previously).
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics