Gal Bracha
Gal Bracha

Reputation: 20011

How to clone an element with data without events with JQuery

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.

Upvotes: 21

Views: 16665

Answers (5)

jave.web
jave.web

Reputation: 15032

If you really just want to copy data attached by the .data() method don't abuse event (un)binding and just do:

var $original = $(".originalSelector");
var $clone = $original.clone().data( $original.data() );

Because when you pass an object to .data() method, it extends the current data with it.

!IMPORTANT NOTE!
You can't do this if you are going to use something that stores DOM references and uses it e.g. jQuery UI draggable etc...
=> only use on "pure" data / basic types

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

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);

Upvotes: 1

Gal Bracha
Gal Bracha

Reputation: 20011

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

Upvotes: 2

Sushanth --
Sushanth --

Reputation: 55740

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();

Upvotes: 11

Adriano Carneiro
Adriano Carneiro

Reputation: 58615

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

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

Upvotes: 21

Related Questions