Choosing between filter and find

The .filter() and .find() jQuery methods look similar, and it could happen to mix them up. Still there is substantial difference between them, .filter() modifies the current set of elements, reducing it by applying the specified rule, while .find() operates on the children of the current set, returning a completely different set of elements.

Say that we are working on an HTML page containing a few lists, and we want to do something on some list items, the LI elements marked with a specific class, and we want to work on the links defined in any list item.

In the first case we'll use the .filter() method, since we want to refine the existing selection, for the latter .find() is the right choice, being our aim to select a new set elements among the children of the original set.

Here is a JavaScript code fragment:
var $li = $("li"); // 1

var $liK = $li.filter('.k'); // 2
console.log($liK, $liK.length);

var $a = $('a'); // 3
var $liA = $li.find('a'); // 4
var $LiA2 = $('a', $('li')); // 5
var $LiA3 = $('li a'); // 6
console.log($a, $a.length, " -", $liA, $liA.length, " -", $liA2, $liA2.length, " -", $liA3, $liA3.length);
1. Selecting all the LI elements in the current document.
2. Restricting the original set to the LI elements having class='k' as attribute.
3. All the anchor elements in the document.
4. Find the anchor elements children of LI elements.
5. Same result of (4), asking to jQuery to get all the A elements children of a LI.
6. Same of (4) and (5), and in this case probably the preferred way to the result.

No comments:

Post a Comment