jQuery: one-liner for removing all children but one
- by user1352530
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!