gates gates - 5 months ago 19
jQuery Question

How to append child div into a parent div using jquery on the click of a button

<div class="addMore">
<div class="row addPlus">
<p class="emergencyTitle">Child 1</p>
<div class="col-xs-6">
<form role="form">
<div class="form-group">
<label for="name">Student Name</label>
<input type="text" class="form-control" name="ch1_name">
</div>
<div class="form-group">
<label for="name">Class</label><br>
<select name="ch1_class">
<option value=""> 1 </option>
<option value=""> 2</option>
<option value=""> 3 </option>
</select>
</div>

</form>
</div>
<div class="col-xs-6">
<form role="form">
<div class="form-group">
<label for="name">DOB</label>
<input type="text" class="form-control" name="ch1_dob" id="datepicker">
</div>
<div class="form-group">
<label for="name">Section</label><br>
<select name="ch1_secion">
<option value=""> A </option>
<option value=""> B </option>
<option value=""> C </option>
</select>
</div>
</form>
</div>
</div>
</div>


On the click of a button I am doing this ..

$child = $('.addPlus')
$('.addMore').append($child)


But I cannot seem to add the addPlus div, how over
$('.addMore').append("hi")
works fine. Can anyone help me out where I am going wrong.

Answer

.addPlus is already appended to .addMore, so your jQuery would work but have no effect.

Assuming you want to copy the existing instance of .addPlus you should call clone() on it before appending it to the parent, like this:

var $newChild = $('.addPlus').first().clone()
$('.addMore').append($newChild)