Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone an element with data without events with JQuery

Tags:

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.

like image 333
Gal Bracha Avatar asked Oct 30 '12 15:10

Gal Bracha


People also ask

Do events also get copied when you clone an element in jQuery?

Well the default implementation of the clone() method doesn't copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.

How do you clone an object in jQuery?

To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.

How does jQuery clone work?

The . clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.


2 Answers

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

$('#grolsh').clone(true).off();
like image 81
Adriano Carneiro Avatar answered Sep 29 '22 21:09

Adriano Carneiro


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

like image 28
Sushanth -- Avatar answered Sep 29 '22 20:09

Sushanth --