modern-web-design-and-development

(Brent) #1

One of the great things about this is that you can also iterate over objects
— but only in the first way (i.e. $.each).


jQuery is known as a DOM-manipulation and effects framework, quite
different in focus from other frameworks such as MooTools, but each() is
an example of its occasional foray into extending JavaScript’s native API.


.filter()


filter(), like each(), visits each element in the chain, but this time to
remove it from the chain if it doesn’t pass a certain test.


The most common application of filter() is to pass it a selector string,
just like you would specify at the start of a chain. So, the following are
equivalents:


1 $('p.someClass').css('color', '#f90');
2 $('p').filter('.someclass').css('color', '#f90');

In which case, why would you use the second example? The answer is,
sometimes you want to affect element sets that you cannot (or don not
want to) change. For example:


1 var elements = $('#someElement div ul li a');
2 //hundreds of lines later...
3 elements.filter('.someclass').css('color', '#f90');

elements was set long ago, so we cannot — indeed may not wish to —
change the elements that return, but we might later want to filter them.


filter() really comes into its own, though, when you pass it a filter
function to which each element in the chain in turn is passed. Whether the

Free download pdf