Search code examples
javascriptjquerytwitter-bootstrapclone

Change inner elements id during clone


I'm doing a clone of a DIV element on button click, I'm able to change the value of ID of the DIV element I'm cloning. But is it possible to change the id of the inner element.

In the below code I'm changing the Id of #selection while cloning, I need to dynamically change the id #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>

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

Solution

  • Yes.. its totally 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);