How to clone and change id?

199,459

Solution 1

$('#cloneDiv').click(function(){


  // get the last DIV which ID starts with ^= "klon"
  var $div = $('div[id^="klon"]:last');

  // Read the Number from that DIV's ID (i.e: 3 from "klon3")
  // And increment that number by 1
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
  var $klon = $div.clone().prop('id', 'klon'+num );

  // Finally insert $klon wherever you want
  $div.after( $klon.text('klon'+num) );

});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

<button id="cloneDiv">CLICK TO CLONE</button> 

<div id="klon1">klon1</div>
<div id="klon2">klon2</div>

Scrambled elements, retrieve highest ID

Say you have many elements with IDs like klon--5 but scrambled (not in order). Here we cannot go for :last or :first, therefore we need a mechanism to retrieve the highest ID:

const all = document.querySelectorAll('[id^="klon--"]');
const maxID = Math.max.apply(Math, [...all].map(el => +el.id.match(/\d+$/g)[0]));
const nextId = maxID + 1;

console.log(`New ID is: ${nextId}`);
<div id="klon--12">12</div>
<div id="klon--34">34</div>
<div id="klon--8">8</div>

Solution 2

Update: As Roko C.Bulijan pointed out.. you need to use .insertAfter to insert it after the selected div. Also see updated code if you want it appended to the end instead of beginning when cloned multiple times. DEMO

Code:

   var cloneCount = 1;;
   $("button").click(function(){
      $('#id')
          .clone()
          .attr('id', 'id'+ cloneCount++)
          .insertAfter('[id^=id]:last') 
           //            ^-- Use '#id' if you want to insert the cloned 
           //                element in the beginning
          .text('Cloned ' + (cloneCount-1)); //<--For DEMO
   }); 

Try,

$("#id").clone().attr('id', 'id1').after("#id");

If you want a automatic counter, then see below,

   var cloneCount = 1;
   $("button").click(function(){
      $("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
   }); 

Solution 3

This is the simplest solution working for me.

$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");

Solution 4

This works too

 var i = 1;
 $('button').click(function() {
     $('#red').clone().appendTo('#test').prop('id', 'red' + i);
     i++; 
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="test">
  <button>Clone</button>
  <div class="red" id="red">
  </div>
</div>

<style>
  .red {
    width:20px;
    height:20px;
    background-color: red;
    margin: 10px;
  }
</style>

Solution 5

I have created a generalised solution. The function below will change ids and names of cloned object. In most cases, you will need the row number so Just add "data-row-id" attribute to the object.

function renameCloneIdsAndNames( objClone ) {

    if( !objClone.attr( 'data-row-id' ) ) {
        console.error( 'Cloned object must have \'data-row-id\' attribute.' );
    }

    if( objClone.attr( 'id' ) ) {
        objClone.attr( 'id', objClone.attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
    }

    objClone.attr( 'data-row-id', objClone.attr( 'data-row-id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );

    objClone.find( '[id]' ).each( function() {

        var strNewId = $( this ).attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } );

        $( this ).attr( 'id', strNewId );

        if( $( this ).attr( 'name' ) ) {
            var strNewName  = $( this ).attr( 'name' ).replace( /\[\d+\]/g, function( strName ) {
                strName = strName.replace( /[\[\]']+/g, '' );
                var intNumber = parseInt( strName ) + 1;
                return '[' + intNumber + ']'
            } );
            $( this ).attr( 'name', strNewName );
        }
    });

    return objClone;
}
Share:
199,459
user1324780
Author by

user1324780

Updated on June 17, 2021

Comments

  • user1324780
    user1324780 almost 3 years

    I need to clone the id and then add a number after it like so id1, id2, etc. Every time you hit clone you put the clone after the latest number of the id.

    $("button").click(function() {
        $("#id").clone().after("#id");
    }); 
    
  • Blazemonger
    Blazemonger about 12 years
    You missed a great opportunity to use 'id'+ ++ id in your code.
  • Selvakumar Arumugam
    Selvakumar Arumugam about 12 years
    @RokoC.Buljan You are right, but the question was how to change the attr of the cloned element and so I missed to notice the .after. See updated answer.
  • Selvakumar Arumugam
    Selvakumar Arumugam about 12 years
    +1 for Working demo :) and Thanks for looking over my answer. I have updated the post also added a working demo jsfiddle.net/HGtmR/4
  • Roko C. Buljan
    Roko C. Buljan about 12 years
    :) +1 to round it to 5 ! ;) nice use of [id^=id]:last Congrats.
  • user1324780
    user1324780 about 12 years
    is it also possible to have a button inside the div that removes the current id div?
  • Selvakumar Arumugam
    Selvakumar Arumugam about 12 years
    @user1324780 Yes it is possible, but you should post that as a new question. Anyways the clue is to find the .closest(div[id^=id]) and .remove that div.
  • Optiq
    Optiq over 8 years
    can this be applied to names as well?
  • Nicolas Manzini
    Nicolas Manzini over 8 years
    fit perfectly my need. It saved me hours of development most likely! thanks
  • user3058963
    user3058963 almost 4 years
    How to use this with $(this)?? It is not work $(this).('div[id^="picker-time-start"]');
  • Roko C. Buljan
    Roko C. Buljan almost 4 years
    @user3058963 learn how to use jQuery. Your code is not valid.
  • user3058963
    user3058963 almost 4 years
    @RokoC.Buljan your answer does not contribute anything
  • Roko C. Buljan
    Roko C. Buljan almost 4 years
    @user3058963. Comment sections are not meant to contribute to, or discuss unrelated specific problems. Said that, might be you're missing .find() or might be something completely different. If you have a problem please do a research, and Ask a New Question. And please take a tour to better understand how this pages work.