<ul> <li class="1" /> <li class="2" /> <li class="3" /> <li class="4" /> <li class="5" /> </ul>
The filter iterates over a collection of jQuery objects. For each of the elements: Return true inside filter() to save the current element in the jQuery collection of objects. Return false to remove the current object from the jQuery object collection.
$("li").filter(function () { if (this.className == "1" || this.className == "2") return true; return false; });
In this case; the anonymous function executed by filter() will return true for a list item that has class 1 and / or 2, in turn removing the last three list items from the jQuery collection of objects.
A practical example:
<ul> <li class="1" /> <li class="2" /> <li class="3" /> <li class="4" /> <li class="5" /> </ul>
This snippet adds the class ("blue") to the unordered list. Then the first two lists are highlighted. It then attaches the click handler to the first two elements of the list:
$(function () { $("ul").addClass("blue").find("li").filter(function () { if (this.className == "1" || this.className == "2") return true; return false; }).addClass("highlight").click(function () { alert("I am highlighted!"); }); });
cllpse Sep 10 '09 at 13:01 2009-09-10 13:01
source share