Skip to main content

jQuery Filter Function Example

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Just a quick couple of examples for one of jQuery’s underused functions. The $.filter() function is probably not used as much as more popular functions such as $.find() because it offers a slower speed according to jsperf.

jsperf-find-vs-filter

$.filter() Example 1

Filter all the hyperlinks which target MS Word Documents and PDF’s then attach an event which fires off a Google Analytics custom event tracking.

//checking specific file types
$('a[href]').filter(function()
{
     return /(.pdf|.doc)$/.test($(this).attr('href'));
}).bind('click', function()
{
     _gaq.push(['_trackEvent', window.location.pathname, 'Download', $(this).attr('href')]);
});

$.filter() Example 2

Filter all hyperlinks which target PNG and JPG images… add a nice red border to them.

//get all image links
$('a[href]').filter(function()
{
  return /(jpg|png)$/.test($(this).attr('href'))
}).each(function(i,v)
{
   $(v).css('border','2px solid red');
});

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.