JQuery get all items in a list
Could someone help me out with this JQuery?
I have a bunch of list items, and when clicking one of them, I want to remove the class attribute 'selected' from each list item in the same UL.
I have a javascript function:
<script type='text/javascript'>
function clearSelectedCSS(item) {
$(item).parent().$('li.itemselected').removeClass('itemselected');
}
</script>
It is called via the onclick part of each LI, and 'this' is passed.
I can't quite figure out the JQuer开发者_开发技巧y, could someone give me a pointer? My code basically wants to select the item that was clicked, get its parent, then select all list items that belong to that parent (ie, every li in the list that was clicked that has class 'itemselected'), then remove the class 'itemselected' from them all.
No need to get the .parent()
when you can just grab the .siblings()
:
$(item).siblings('.itemselected').removeClass('itemselected');
This will be more efficient, because .parent().find()
will test all descendant elements. Even if you did .parent().children()
, you're adding an unnecessary traversal.
EDIT: I'm not sure from the question if you want to include the one that was clicked in the class removal.
If so, you could do this:
$(item).parent().children('.itemselected').removeClass('itemselected');
or
$(item).siblings().andSelf().filter('.itemselected').removeClass('itemselected');
$(item).parent().find('li.itemselected').removeClass('itemselected');
If you want to select all lis except the one that was clicked, you can use $().siblings()
:
$(item).siblings('li.itemselected').removeClass('itemselected');
Using parent().find('li.itemselected')
will include the <li>
that was clicked.
I played around with this until I got this to work:
<head>
<script>
function clearSelectedCSS(item) {
$('#' + item.parentElement.id + ' > li').removeClass('exampleClass');
}
</script>
</head>
<body>
<form id="form1">
<ul id="List1">
<li class="exampleClass" onclick="clearSelectedCSS(this)">First Item</li>
<li class="exampleClass" onclick="clearSelectedCSS(this)">Second Item</li>
<li class="exampleClass" onclick="clearSelectedCSS(this)">Third Item</li>
</ul>
<ul id="List2">
<li class="exampleClass" onclick="clearSelectedCSS(this)">Fourth Item</li>
<li class="exampleClass" onclick="clearSelectedCSS(this)">Fifth Item</li>
<li class="exampleClass" onclick="clearSelectedCSS(this)">Sixth Item</li>
</ul>
</form>
</body>
</html>
Basically, I had to address the parent of the item to get the <ul>
container object, and then used the >
child selector to get the collection of <li>
. At that point the .removeClass()
call works correctly. Hope that helps--
精彩评论