Sam Sam - 5 months ago 16
jQuery Question

How to remove the next element after removal of parent in Jquery

I have simplified my problem to the following markup:

<div id="A">
<div id="B"></div>
<div id="C"></div>
</div>
<br>


And JQuery JS as in:

$('#B').click(function() {
$(this).parent().remove();
}


It removes A and thats what I want. But I also want to remove the br tag that immediately follows the parent. I tried various combinations of parent(), first(), next() of parent(), parent().parent(), etc... No luck.

Answer

You should use jQuery .is() check to check if the next element is a
and then remove it. Refer Below code and fiddle :

$(document).ready(function() {
  $('#B').click(function() {
    if($(this).parent().next().is('br')) {
      $(this).parent().next().remove()
    }
    $(this).parent().remove();
  });
});

JsFiddle : https://jsfiddle.net/nikdtu/3xx2L20h/