Sunday, April 3, 2011

Why does my jQuery fadeOut/remove get rid of the parent DOM element?

I have a list of items for example:

<li class="ui-state-default" ><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>test <a href="#" title="Delete" class="itemDelete">x</a></li>

$('.itemDelete').live("click", function() {

                $(this).parent().remove();
            });

All is ok. If I change it to

$(this).parent().fadeOut("slow", function() { $(this).parent().remove(); });

It seems to remove the <li> ok but also the <li> above it. I've tried running the fade then the remove on separate lines but that appears to the user as if its just done a remove and not the fade.

Any ideas?

From stackoverflow
  • It's an issue of what this refers to — in the callback, this is your faded element. You want:

    $(this).parent().fadeOut("slow", function() { $(this).remove(); });
    
    Jon : Thanks, I assume this in the callback is the object that has been faded?
    Blixt : @Jon: It is, yes.
  • You're removing the parent's parent. Change it to:

     $(this).parent().fadeOut("slow", function() { $(this).remove(); });
    

0 comments:

Post a Comment