0

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

     function removeDiv(){
            $(this).parent('div').remove();
        }
   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
        <div>
            <div><button onClick="removeDiv()">button1</button></div>
        </div>
        <div>
            <div><button onClick="removeDiv()">button2</button></div>
        </div>
    </div>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Bas
  • 2,330
  • 4
  • 29
  • 68
  • 2
    `onClick="removeDiv(this)"` and `function removeDiv(elem){ $(elem).parent('div').remove(); }` – Satpal Nov 04 '16 at 11:05

2 Answers2

4

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>
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

using with jquery simply add the click event: like blew.Its will be remove the closest parent div

Two Methods:

   1.$(this).parent('div').remove();

   2.$(this).closest('div').remove();

$(document).ready(function (){
$('button').click(function (){
        $(this).parent('div').remove();
  //$(this).closest('div').remove(); its also working
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div>
        <div><button >remove1</button></div>
    </div>
    <div>
        <div><button >remove2</button></div>
    </div>
</div>
prasanth
  • 22,145
  • 4
  • 29
  • 53