-1

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
  • 34,719
  • 24
  • 185
  • 251
Bas
  • 2,213
  • 3
  • 27
  • 62
  • 2
    `onClick="removeDiv(this)"` and `function removeDiv(elem){ $(elem).parent('div').remove(); }` – Satpal Nov 04 '16 at 11:05

2 Answers2

3

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
  • 129,808
  • 12
  • 152
  • 166
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
  • 21,342
  • 4
  • 27
  • 50