Reputation: 9090
There is a tree style structure from which I want to keep only a specific branch.
The list is like:
ul.level-1
--li
----ul.level-2
------li
------li
--li
----ul.level-2
------li
------li
------li
By giving the element I've selected (a second level li
element), I want to remove all top level li
except the one this li
belongs to.
Is this possible without iterating within the tree?
Upvotes: 3
Views: 83
Reputation: 2534
try this demo
$("li").click(function(){
$(this).parents("li").siblings().remove();
});
Upvotes: 0
Reputation: 262929
You can do something like:
$("li").click(function() {
var $this = $(this);
$this.closest("ul.level-1").children("li").filter(function() {
return !$this.closest(this).length;
}).remove();
});
First, closest() is used to match the top-level <ul>
element. Then for each of its children <li>
elements, filter() is used with closest()
to check if the clicked <li>
element is a descendant of the current list item, or that list item itself. This excludes the clicked item's branch, and remove() is called on the rest.
Upvotes: 1
Reputation: 12579
If I understand you correctly, this should do what you need:
$('li.selected').closest('li.toplevel').siblings('li').remove();
Upvotes: 1
Reputation: 144689
Try this:
$('.level2 li').click(function(){
$(this).closest('li').siblings().remove()
})
Upvotes: 1