Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove DIV on Click

Tags:

jquery

I have a DIV which I want to be removed when I click a link contained inside that DIV. Here is what I have:

<div id="clients-edit-wrapper">
    <div class="close-wrapper">
        <a href="#" class="close-div">Close</a>
    </div>
</div>

When I click "Close" I want clients-edit-wrapper to be removed. I'm looking for a way to do this by referencing the parent DIV of the Close link which, in this case, is clients-edit-wrapper.

Any help would be greatly appreciated!


Answer from Huangism below:

$('.close-div').click(function(){
   $(this).parent().parent().remove();
});

This only works if the element you would like to remove is two parents up. In my case, this is exactly what I needed.

like image 418
FastTrack Avatar asked Jun 15 '12 20:06

FastTrack


2 Answers

given your html markup

Updated to .on()

$('.close-div').on('click', function(){
    $(this).closest("#clients-edit-wrapper").remove();
});

More flexibility with .closest, this gives you the option to have more more parents or less parents.

https://api.jquery.com/closest/

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Edit
(Added related resources)
Please see jQuery documentation on live()

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

As far as I know this is due to memory concerns/issues with live().

like image 88
Huangism Avatar answered Oct 13 '22 03:10

Huangism


Here is one solution:

$(".close-div").on("click", function(event) {
    $("#clients-edit-wrapper").remove();
    event.preventDefault();
});

To get #clients-edit-wrapper element relatively to .close-div element, you can use either parent().parent() or closest with ID:

$(this).parent().parent().remove();                  // will do
$(this).closest("#clients-edit-wrapper").remove();   // the same

However, the last doesn't make sense, since IDs of page elements should be unique, and there won't be another #clients-edit-wrapper.

like image 34
VisioN Avatar answered Oct 13 '22 04:10

VisioN