How to clone an element with data without events with JQuery

15,033

Solution 1

As from version 1.7, off() is the preferred method for unbinding:

$('#grolsh').clone(true).off();

Solution 2

Just use

$('#grolsh').clone(); // Copies the element structure

$('#grolsh').clone(true) // Copies both data and events along with the structure

$('#grolsh').clone(true).off() // Copies both data and events and removes handlers

Events bound with .on() and removed using .off();

Events bound with .bind() and removed using .unbind();

Solution 3

By adding an .off():

$('#grolsh').clone(true)
    .attr({'id': 'newGrolsh'})
    .off()
    .appendTo('#target');

Updated: As Adrian suggested .off would be a better solution over .unbind

Solution 4

As of from jQuery version 1.5, you can pass second parameter (See: .clone( [withDataAndEvents ] [, deepWithDataAndEvents ] ))not to copy the event handler:

$('#grolsh').clone(true,false);
Share:
15,033

Related videos on Youtube

Gal Bracha
Author by

Gal Bracha

Developing for Positive Impact. Helping communities and individuals make a better world. Current Project Genetics and AI https://emedgene.com/ Open source: A platform to organize a community in a decentralized way https://github.com/Metaburn/doocrate/ https://website.doocrate.com A platform to plan co-created art funds: http://dreams.midburnerot.com/?lang=en https://github.com/metaburn/dreams/ Fluid dynamics: https://github.com/rootux/visionquest - Real-time GPU based fluid dynamic system that translates data from a depth sensor /high-speed camera. Other social accounts Facebook Twitter Linkedin Medium My old blog posts

Updated on June 17, 2022

Comments

  • Gal Bracha
    Gal Bracha over 1 year

    I want to clone a <select> tag with it's data attribute but without its events.

    Following JQuery Official .clone() api, I understand I can clone without data and events by calling $('#grolsh').clone(), or perform a

    $('#grolsh').clone(true) which will copy data and events.

    I want to keep the data but clear the events associates with the original item.

  • Gal Bracha
    Gal Bracha about 11 years
    So what is the difference between .off() and .unbind()?
  • charlietfl
    charlietfl about 11 years
    first case is not true, data isn't copied with clone() and no arguments jsfiddle.net/ALxz4
  • Adriano Carneiro
    Adriano Carneiro about 11 years
  • Gal Bracha
    Gal Bracha about 11 years
    The docs states "As of jQuery 1.4, all element data (attached by the .data() method) is also copied to the new copy." but from my testing, normal clone() didn't copy the data
  • jave.web
    jave.web over 7 years
    Nope, that is just "A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. " - it may seem like it if your #grolsh does not have any events, just data... but it is not like that.