Krishh
Krishh

Reputation: 4231

Remove all other list items except the one that is clicked using jQuery

I have list of this kind

<ul>
<li><div class="pname">Name1</div><div class="pid">ID1</div>...</li>
<li><div class="pname">Name2</div><div class="pid">ID2</div>...</li>
<li><div class="pname">Name3</div><div class="pid">ID3</div>...</li>
...
</ul>

If I click on any of the list item, rest all other list items should be removed. Can anyone suggest how I could do this?

Upvotes: 1

Views: 2031

Answers (3)

65Fbef05
65Fbef05

Reputation: 4522

jQuery solution...

$('li').click(function() {
    $(this).siblings().remove();
});

Upvotes: 0

mVChr
mVChr

Reputation: 50185

You can simply replace the ul contents with the clicked item:

$('ul li').click(function(ev){
    $(this).closest('ul').html($(this));
});​

See demo

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318518

Assuming this is the clicked li element:

$(this).siblings('li').not(this).remove();

If the click handler is bound to something inside the list item:

$(this).closest('li').siblings('li').not($(this).parents()).remove();

Upvotes: 9

Related Questions