Changing the internal id element during cloning

I clone the DIV element when I click the button, I can change the identifier value of the DIV element that I cloned. But is it possible to change the identifier of the inner element.

In the code below, I change the identifier #selectionwhen cloning, I need to dynamically change the identifier #select.

<div id="selections">
  <div class="input-group" id="selection">
    <span class="input-group-addon">
    <i class="icon wb-menu" aria-hidden="true"></i>
     </span>
    <select class="show-tick" data-plugin="select2" id="select">
      <option>True</option>
      <option>False</option>
    </select>
  </div>
</div>
<button class="btn btn-primary" type="button" style="margin-left: 30px;">
  Add new selection
</button>

Js below

$(function() {
  //on click
  $("body").on("click", ".btn-primary", function() {
    alert($(".input-group").length)
    var
    //get length of selections
      length = $(".input-group").length,
      //create new id
      newId = "selection-" + length++,
      //clone first element with new id
      clone = $("#selection").clone().attr("id", newId);
    //append clone on the end
    $("#selections").append(clone);
  });
});
+8
source share
4 answers

Yes .. its quite possible as follows:

var clone = $("#selection").clone();
clone.attr("id", newId);

clone.find("#select").attr("id","select-"+length);

//append clone on the end
$("#selections").append(clone); 
+15
source

You need to change all the child IDs manually.

Or change it to just one:

//clone first element with new id
clone = $("#selection").clone();
clone.attr("id", newId);
clone.find("#select").attr("id","whateverID");

, - : jQuery, id

+1

Use the .show-tickand method .children()to search for an element:

clone.children('.show-tick').attr('id', 'select-' + length);

$(function() {
  //on click
  $(".btn-primary").on("click", function() {
    alert($(".input-group").length)
    var
    //get length of selections
      length = $(".input-group").length,
      //create new id
      newId = "selection-" + length,
      //clone first element with new id
      clone = $("#selection").clone().attr("id", newId);
      clone.children('.show-tick').attr('id', 'select-' + length++);
    //append clone on the end
    $("#selections").append(clone);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selections">
  <div class="input-group" id="selection">
    <span class="input-group-addon">
    <i class="icon wb-menu" aria-hidden="true"></i>
     </span>
    <select class="show-tick" data-plugin="select2" id="select">
      <option>True</option>
      <option>False</option>
    </select>
  </div>
</div>
<button class="btn btn-primary" type="button" style="margin-left: 30px;">
  Add new selection
</button>
Run code
+1
source

what is the code for pure javascript?

0
source

Source: https://habr.com/ru/post/1613848/


All Articles