jQuery: one-liner for removing all children but one
Posted
by
user1352530
on Stack Overflow
See other posts from Stack Overflow
or by user1352530
Published on 2012-09-28T15:20:54Z
Indexed on
2012/09/28
15:37 UTC
Read the original article
Hit count: 251
HTML code is:
<li>
<a href="#" />
<ul>
<li>
<a href="#"/>
</li>
</ul>
</li>
I want to delete any node under $(this) = li that is not a link. If there are more than one link, just the first one is saved, and if there are links inside the ul tag, they are not included because they are descendants and no childrens.
Something like this (I am cloning and outputting html):
$(this).clone().remove('not(a:first)').html(); //Assuming remove looks for "a" as a first child
Does not work, so I try with this:
$(this).clone().children().remove('not(a:first)').parent().html();
Does not work so I try with this:
$(this).clone().remove('not(>a:first)').html();
I need the original element as a reference after removal for chaining more operations
EDIT: Ok! Second one works with a little syntax correction as some appointed (:not( instead of not() but I would like to know if there is any other solution similar to the third line so I don't have to do children().remove().parent(). Thank you!
© Stack Overflow or respective owner