modern-web-design-and-development

(Brent) #1

function returns true or false determines whether the element stays in
the chain. For example:


1 $('p').filter(function() {

(^2) return $(this).text().indexOf('hello') != -1;
3 }).css('color', '#f90')
Here, for each

found in the document, if it contains the string hello,
turn it orange. Otherwise, don’t affect it.
We saw above how is(), despite its name, was not the equivalent of not
(), as you might expect. Rather, use filter() or has() as the positive
equivalent of not().
Note also that unlike each(), filter() cannot be used on arrays and
objects.


Real-Life Example


You might be looking at the example above, where we turned

s starting
with hello orange, and thinking, “But we could do that more simply.”
Yo u ’d b e r i g h t :


1 $('p:contains(hello)').css('color', '#f90')

For such a simple condition (i.e. contains hello), that’s fine. But filter()
is all about letting us perform more complex or long-winded evaluations
before deciding whether an element can stay in our chain.


Imagine we had a table of CD products with four columns: artist, title, genre
and price. Using some controls at the top of the page, the user stipulates
that they do not want to see products for which the genre is “Country” or

Free download pdf