javascript - jQuery: Add Sibling of Parent to Current Matched Elements -
i'm trying - in 1 line - remove parent element of clicked element , parent's lone sibling element. two-liner solution here:
$(document).ready(function() { $('.close').click(function() { $(this).parent().siblings('.sibling').remove(); $(this).parent().remove(); }); });
here's working fiddle. i'm looking avoid navigating dom twice since i've found parent of clicked element when remove sibling, there's no reason should doing again. i'm aware wrap both parent , sibling in element , remove super element, @ point i'd avoid well.
i've looked using jquery's .add()
function, can't seem work. help!
you're looking .addback()
:
$(this).parent().siblings('.sibling').addback().remove();
andself
equivalent.addback()
jquery < 1.8
with .add()
, have store parent in variable avoid traversing twice:
var $father = $(this).parent(); $father.siblings('.sibling').add($father).remove(); //one-liner without storing in variable traverse dom twice: $(this).parent().siblings('.sibling').add($(this).parent()).remove();
as can see, addback
method more practical in case.
in case element's parent , parent's sibling elements inside parent, can use:
$(this.parentnode.parentnode).empty();
the native parentnode
property bit faster jquery's .parent()
method. use.
note such small traversing has little overhead either way. original code , these versions have little difference performance-wise.
Comments
Post a Comment