Gagan Gagan - 4 months ago 8
jQuery Question

How to remove all the elements other than the last element in a HTML form

I have a html form as follows

<div class="control-group" id="fields">
<label for="">Use this section to add as many execution steps as you would like for this test case.</label>
<div class="controls">
<form role="form" autocomplete="off" id="formStep">
<div class="entry input-group col-sm-12" style="margin-bottom:3px;">
<input class="form-control stepFields" name="fields[]" type="text" placeholder="test step">
</div>
<div class="entry input-group col-sm-12" style="margin-bottom:3px;">
<input class="form-control stepFields" name="fields[]" type="text" placeholder="test step">
</div>
<div class="entry input-group col-sm-12" style="margin-bottom:3px;">
<input class="form-control stepFields" name="fields[]" type="text" placeholder="test step">
</div>
<div class="entry input-group col-sm-12" style="margin-bottom:3px;">
<input class="form-control stepFields" name="fields[]" type="text" placeholder="test step">
</div>
</form>
<br>

</div>
</div>


and I have the following JS (Jquery)

$('.controls form')
.not($(this).children('.entry').last()[0])
.remove();


What I would like to do is to remove all the divs with the class name
entry
except the last one ?

Can you please let me know what I am doing wrong here ?

Thanks

Answer

Use a combination of find() and not()

Try the following

 $('.controls form').find('.entry').not(':last').remove(); 

demo

Comments