Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to Clone HTML Elements in jQuery with new ID and Name?

Tags:

html

jquery

I want to clone one row of a table, but when I clone, the new element's name and id will be the same as the element from which it was cloned.

What I need is the cloned elements with a different name and id.

like image 413
Poonam Bhatt Avatar asked Dec 23 '11 05:12

Poonam Bhatt


People also ask

How do I clone a div with another ID?

To clone an element and change its id: Use the cloneNode() method to clone the element. Set a different id property on the element. For example, clone.id = 'another-id' .

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 do you clone in HTML?

The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).


2 Answers

I would pass prop a map of key/value pairs to update these values after cloning:

$("#selector").clone().prop({ id: "newId", name: "newName"});

Cloned elements don't exist in the DOM until you add them, so you're not going to have to worry about duplicate ids until you do that.

Example: http://jsfiddle.net/BbpRA/

Update: In the comment you say you have 20 inputs you need to clone. I would create a function that takes the DOM element and the new id and name. You could even make a small plugin out of it:

(function($) {
    $.fn.cloneWithProperties = function (properties) {
        return this.clone().prop(properties);
    };
})(jQuery)

Usage:

$("#selector").cloneWithProperties({ id: "newId", name: "newName" });
like image 68
Andrew Whitaker Avatar answered Oct 05 '22 09:10

Andrew Whitaker


You can do something like:

var x = $("#selector").clone();

x.find('#oldID1').attr({id: "newID1", name: "newName1"});
x.find('#oldID2').attr({id: "newID2", name: "newName2"});
...

Once its done, you can append x to wherever you want.

Pls note that the #selector above refers to your table row element.

like image 44
techfoobar Avatar answered Oct 05 '22 09:10

techfoobar