Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone and change id?

People also ask

How to clone div JS?

JavaScript cloneNode() example First, select the <ul> with the id menu by using the querySelector() method. Second, create a deep clone of the <ul> element using the cloneNode() method. Third, change the id of the cloned element to avoid duplicate. Finally, append the cloned element to the child nodes of the document.

How do you assign an ID to a child tag of the cloned HTML?

After cloning the Html code, we are going to change the ID of child tag of <b> and <button> tag by finding the tag using its attribute name such as id, class. After finding the tag using its attribute name, then we are going change its attribute name by jQuery attr() method.

What is cloneNode in JavaScript?

CloneNode() It is a method used to clone an element from one list to another list. The cloneNode(), provided by javascript, the method creates a copy of a node and returns the clone. It can clone all attributes and their values.


$('#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>

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

This is the simplest solution working for me.

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

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>