Bas Bas - 1 month ago 13
jQuery Question

Jquery onlick remove parent div

I have the following code but how can i achieve when clicking on de remove button the parent div removes?

<div>
<div>
<div><button onClick="removeDiv()"></button></div>
</div>
<div>
<div><button onClick="removeDiv()"></button></div>
</div>
</div>

<script>
function removeDiv(){
$(this).parent('div').remove();
}
</script>

Answer

pass the current element context this to removeDiv function.

<div><button onClick="removeDiv(this)"></button></div>

Change function as

function removeDiv(elem){
    $(elem).parent('div').remove();
}

However as you are using jQuery, You should bind event using it, here is an example, where I have used Class Selector (“.class”) to bind event handler with elements.

jQuery(function($) {
  $('.removeDiv').on('click', function() {
    $(this).parent('div').remove();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div>
    <div>
      <button class="removeDiv">removeDiv</button>
    </div>
  </div>
  <div>
    <div>
      <button class="removeDiv">removeDiv</button>
    </div>
  </div>
</div>