jQuery 3 - Filters
Written by Ian Elliot   
Monday, 08 August 2016
Article Index
jQuery 3 - Filters
Simple filters
More Filters

Other Filters

There are a range of other filters which have been added to jQuery in a fairly ad-hoc way. They are useful but they don't fit into any neat patterns or families - they are just useful.

:animated

selects elements in the process of animation at the time the selector is run. Clearly this one isn't really a filter on the results array as it is tied to the time that the query is run. However it is still faster to use

.filter(":animated")

:contains

selects all elements that contain the specified text. The match can be within the element or within any child element. For example :contains(jQuery) will return results that contain the string jQuery with that capitalization. 

:disabled

selects all elements that are disabled at the time the query is run.

:enabled

selects all elements that are enabled at the time the query is run.

:focus 

selects the element that has the current focus. Again this isn't really a filter on the result array because it matters when the query is run. 

:header 

selects all header elements h1,h2 and so on. This one is convertible to a true filter and it is better to use

.filter(":header")

:image

selects all image elements

:lang(language)

Selects all elements with a language attribute as specified. It also extracts elements contained within language specific elements on the assumption that they inherit the language setting unless it is overridden.

:root

Selects the root element of the document - usually html.

:selected

Selects all elements that are selected at the time of the query

:target

Selects the element with the id that matches any fragment identifier in the URL. That is if the URL is www.mysite.com/#mycontrol   then :target selects the element, if any, with an id of mycontrol. 

:visible

Select all elements visible at the time the query is run

There are more miscellaneous filters but the line between filter and selector starts to be increasingly blurred.

After all is :header a selector or a filter?  

There is a tendency in jQuery to call any non-standard selector a filter and this can be confusing. 

Thre are also selectors that work with forms and these are discussed in chapter 8. For completeness these are:

  • :button - select all button elements
  • :checkbox - select all checkbox elements
  • :file - selects all file elements
  • :password - selects all password elements
  • :radio - select all radio buttons
  • :reset - select all reset elements
  • :submit - select all submit elements
  • :text - select all text input elements

The Filter Stack

This is the final twist in the filter story.

If you have been following the description of how filters work then you will appreciate the idea that filters take one jQuery result array and convert it into another filtered result array. What hasn't been mentioned until now is that each time you create a new result array using a filter the old original unfiltered result array is kept just in case you want to use it again. You can restore the old result array in a number of ways, but the simplest is to use the .end() method. 

For example:

$("p");

produces a result array containing all of the p elements.  We can use the eq filter to reduce this to just the first p element and add some text:

$("p").eq(0).append("1");

If we now use .end we can return to the result array that had the entire set of p elements

$("p").eq(0).append("1").end();

Now we can filter again and add some text to the second p element;

$("p").eq(0).append("1").end().eq(1).append("2");

You can continue in this way using .end to return to a previous result array when ever you need to.

Usually this is about as complicated as it gets but each jQuery object maintains a stack of previous results so .end().end() returns to the result that you had before two filtering operations. 

Of course an alternative to using end() is to simply keep the intermediate results:

var result=$("p"):
result.eq(0).append("1"):
result.eq(1).append("2");

The end function and the stack simply makes it possible for you to do the same thing but using a fluent approach.

As well as end() there is also addBack(selector) method which filters the current result and then adds it to the new results. This is of course a silly operation to perform if the filter doesn't select additional elements - there is no point in eliminating some of the elements and then adding them back. This means that it really only makes sense to use it after a traversal filter. 

For example:

$("p").parent("div").addBack();

first selects all p elements, then selects all of the immediate parent div elements and then adds the original p elements back to the result array - note you get all of the p elements. 

You can also add a selector to filter the elements that are added back to the results:

$("p").parent("div").addBack(":eq(0)");

adds only the first p element back to the results.   

If you want to be really advanced there is also the .pushstack() method that will push an array of elements on the results stack and .remove() which pops anything added back off the stack. 

Filter Strategies

One of the most confusing things about filters is that it is often possible to do the same job with a selector.

For example you might start out with a selector that picks out all of the div and p elements and then filter the result down to just the p elements. Clearly you could have extracted just the p elements in the first place. 

If you have a choice of how to obtain a particular result then there are a number of things that should guide you.

The first is to use standard CSS selectors in preference to jQuery extended selectors. Standard CSS selectors are supported by the browser and much faster. 

It is generally faster to search the entire DOM as few times as possible. This means that if you can extract a result array and then use a filter to narrow it down to what you want this is likely to be faster. The filter only accesses the elements of the results array and not the entire DOM. 

Obviously if you can extract a results array once and get different sub-sets from it by applying a filter this is going to be faster.

There are also times when only a filter will do the job. For example, if you want to get the text from the first ten paragraphs in a document you have to use either:

$("p:lt(10)").text();

or

$("p").slice(0,10).text();

Both of which return the concatenated text of the first 10 paragraphs.  

Which is best?

The answer depends on the number of paragraphs in the entire document. The first performs a slow non CSS standard selector on the text but the second extracts all of the paragraph elements which could number thousands and then reduces it to just ten.  

In practice there seems to be little difference between the two using a modern browser.   

 

Now Available as a Print Book: 

 

smallcoverjQuery

You can buy it from:

USA and World     Amazon.com
Canada            Amazon.ca

UK                Amazon.co.uk
France            Amazon.fr
Germany           Amazon.de
Spain             Amazon.es
Italy             Amazon.it
India             Amazon.in
Japan             Amazon.jp

 

The Core UI

  1. Understanding jQuery (Book Only)
  2. The DOM And Selectors
  3. CSS Selectors
  4. The jQuery Object (Book Only)
  5. Filters
  6. Advanced Filters - Traversing The DOM
  7. Modifying DOM Objects
  8. Creating And Modifying The DOM
  9. jQuery Data
  10. Forms
  11. Function Queues
  12. Animation
  13. jQuery UI
  14. jQuery UI Custom Control - Widget Factory
  15. jQuery - Easy Plugins
  16. Getting Started With QUnit Testing

Now Available as a Print Book:

 

jquery2coverYou can buy it from:

USA and World   Amazon.com
Canada          Amazon.ca
UK              Amazon.co.uk
France          Amazon.fr
Germany         Amazon.de
Spain           Amazon.es
Italy           Amazon.it
India           Amazon.in
Japan          
Amazon.jp

 

 

 

Events, Async & AJAX

  1. Events, Async & Ajax (Book Only)
  2. Reinventing Events
  3. Working With Events
  4. Asynchronous Code
  5. Consuming Promises
  6. Using Promises 
  7. WebWorkers
  8. Ajax the Basics - get
  9. Ajax the Basics -  post
  10. Ajax - Advanced Ajax To The Server
  11. Ajax - Advanced Ajax To The Client
  12. Ajax - Advanced Ajax Transports And JSONP
  13. Ajax - Advanced Ajax The jsXHR Object
  14. Ajax - Advanced Ajax Character Coding And Encoding 

 

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin,  or sign up for our weekly newsletter.

 

Banner


JavaScript Jems - Objects with Values

Sometimes it is useful for an object to have a default value so that it can be used in an expression such as object+1 and object+"hello world". In JavaScript this is really easy and it is an important [ ... ]



JavaScript Async - Cache

The cache API is closely associated with Progressive Web Apps but it can be used in any JavaScript program to good effect. This  extract from my recently published book JavaScript Async: Events C [ ... ]


Other Articles

 



Last Updated ( Monday, 08 August 2016 )