Sandeep Kumar Sandeep Kumar - 2 months ago 11
CSS Question

I have to remove parent div through jQuery

I have to remove whole div which having class "input-group". I have to do this by jQuery. I tried through jQuery but div is not removing.

Here is my code,



$(document).ready(function() {
$(".wrapper").on('click', '.rmvBtn', function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="input-group">
<input type="text" class="form-control" name="field_name[]" value="" />
<span class="input-group-addon">
<a href="#" class="rmvBtn" title="Remove field"">
<span class="glyphicon glyphicon-minus"></span>
</a>
</span>
</div>
</div>





Please let me know what errors have in my code ? Thanks in advance.

Answer

Can you please try below code:

$(document).ready(function(){

    $(".wrapper").on('click', '.rmvBtn', function(e){ 
          e.preventDefault();
          $(this).closest('div.input-group').remove();
          x--;
    });

});

$.closest is for traversing up through its ancestors in the DOM tree till we get the match.

In your code; rmvBtn is inside <span> tag. Hence $(this).parent('div') returns you nothing as $.parent() traverse only single level up in DOM tree.