$.clone and .cloneNode

19,429

A few things. You call cloneNode on this not $(this). Second, with cloneNode you can't clone the events associated with the original node, whereas with jQuery's clone, it clones the events and data (if the first flag is set). Setting the second flag of clone clones the original element's children and their elements.

Use accordingly, according to your needs.

Share:
19,429
Andy
Author by

Andy

Updated on June 11, 2022

Comments

  • Andy
    Andy almost 2 years

    I am a bit confused on the difference between jQuery $.clone and the raw .cloneNode property.

    If I am doing

    $('blah').cloneNode(true) this will create a global object outside of the jQuery space.

    If I use

    $('blah').clone(true) this will create a jQuery object inside the jQuery space but copy everything including events ?

    If I am using jQuery should I stick with .clone and if I change my code from .cloneNode will there any effect ?

  • Paul Bruno
    Paul Bruno about 12 years
    To answer your first question, yes it will copy events, but not the children or their events.
  • Paul Bruno
    Paul Bruno about 12 years
    And to answer your second question, yes, I'd use clone if jQuery was the library primarily used. But it's a matter of preference, and you'll still have to append each new node back into a containing element using either cloning method.
  • Paul Bruno
    Paul Bruno about 12 years
    Finally, if you're looking for good reference material, here's jQuery's clone: http://api.jquery.com/clone/ And here's the DOM's cloneNode: https://developer.mozilla.org/en/DOM/Node.cloneNode
  • john ktejik
    john ktejik over 9 years
    Doesn't Jquery's clone() call cloneNode()? I thought I saw that while looking through the code once...