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

后端 未结 4 1581
日久生厌
日久生厌 2020-12-11 01:42

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.

相关标签:
4条回答
  • 2020-12-11 02:16

    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.

    0 讨论(0)
  • 2020-12-11 02:31

    You can automate your clone with cloneJS. It's just a beta version: CloneJS

    0 讨论(0)
  • 2020-12-11 02:32

    You could try something like this:

    <div class="container">
      <div class="goodbye">
        Goodbye
        <div id="h1" class="hello">Hello</div>
      </div>
    </div>
    
    $('#h1').clone().attr('id','h2').appendTo('.container');
    
    0 讨论(0)
  • 2020-12-11 02:35

    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" });
    
    0 讨论(0)
提交回复
热议问题