Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Buttons Parent Container in Jquery

I guess this is a very basic question, but I have not been able to figure out the proper way to use "remove".

I want to use Jquery to make a button which deletes its parent container. Here is my Fiddle and Code.

As of now nothing happens, I havent even been getting a console error.

I have tried other methods (instead of "parents") including closest, with similar outcomes. Fiddle

  <div class="delete_me">
<h3>Delete Me</h3>
<div>
    <input type="text" placeholder="DELETE ME">
</div>
<button name="button" onclick="removeThis();" type="button">Delete everything in my parent div</button>

function removeThis(){
    $(this).parents('.delete_me').remove();
};
like image 339
WhyEnBe Avatar asked Jun 10 '26 17:06

WhyEnBe


2 Answers

Updated fiddle.

I guess that you can't add an id or an class so you have to pass the the object clicked to the function, example :

HTML :

<button name="button" onclick="removeThis(this);" type="button">Delete everything in my parent div</button>

JS :

function removeThis(_this){
    $(_this).parents('.delete_me').remove();
};

NOTE : If you can add id or class use solution in the other answers because Inline Event Handlers are really not recommended.

Hope this helps.

like image 97
Zakaria Acharki Avatar answered Jun 12 '26 07:06

Zakaria Acharki


Here man: https://jsfiddle.net/leojavier/t375qrwL/4/

<div class="delete_me">
    <h3>Delete Me</h3>
    <div>
        <input type="text" placeholder="DELETE ME">
    </div>
    <button name="button" type="button">Delete everything in my parent div</button>
 </div>

JS

$('button').on('click', function(){
    $(this).parent().remove();
});
like image 31
Leo Javier Avatar answered Jun 12 '26 06:06

Leo Javier