简体   繁体   中英

jQuery: Add Sibling of Parent to Current Matched Elements

I'm trying to - in one line - remove the parent element of a clicked element and the parent's lone sibling element. This is my two-liner solution here:

$(document).ready(function() {
    $('.close').click(function() {
        $(this).parent().siblings('.sibling').remove();
        $(this).parent().remove();
    });
});

Here's a working fiddle. I'm looking to avoid navigating the DOM twice since I've already found the parent of the clicked element when I remove the sibling, there's no reason I should be doing it again. I'm aware that I could wrap both the parent and sibling in an element and just remove that super element, but at this point I'd like to avoid that as well.

I've looked into using jQuery's .add() function, but I can't seem to get that to work. Thanks for your help!

You're looking for .addBack() :

$(this).parent().siblings('.sibling').addBack().remove();

Demo

  • andSelf is an equivalent to .addBack() for jQuery < 1.8

With .add() , you would have to store the parent in a variable to avoid traversing to it twice:

var $father = $(this).parent();
$father.siblings('.sibling').add($father).remove();
//one-liner without storing in a variable would traverse the DOM twice:
$(this).parent().siblings('.sibling').add($(this).parent()).remove();

As you can see, the addBack method is more practical in this case.

In case the element's parent and the parent's sibling are the only elements inside their parent, you can also use:

$(this.parentNode.parentNode).empty();

Demo

The native parentNode property is a bit faster than jQuery's .parent() method. It is up to which to use.


Note that such small traversing has very little overhead either way. Your original code and these versions have very little difference performance-wise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM