Getting Started With jQuery - Filters
Written by Ian Elliot   
Saturday, 25 October 2014
Article Index
Getting Started With jQuery - Filters
Simple filters

Mastering the core of jQuery is first a matter of understanding selectors and then DOM manipulation. Filters are often confused with selectors but they are quite different and serve an important purpose.

There is a newer version of this article:

Query 3 - Filters

 

  

jquerycover

Chapter List 

  1. The DOM
  2. CSS Selectors
  3. Filters
  4. Advanced Filters
  5. Manipulating The DOM
  6. Promises & Deferred
  7. Promises, Deferred & WebWorkers
  8. Ajax the Basics - get
  9. Ajax the Basic -  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
  15. jQuery - Easy Plugins
  16. jQuery UI
  17. jQuery UI Custom Control - Widget Factory
  18. Getting Started With QUnit Testing

 

The jQuery Result Object

When you start using jQuery one of the first things you learn is how to make use of selectors to extract elements from the DOM. 

For example:

$("p");

selects all of the <p> elements in a page. 

Often you make use of the extracted elements immediately. For example:

$("p").append("<p>Hello</p>");

adds a paragraph with content "Hello" after every paragraph extracted by the selector "p". 

Some jQuery operations work on all of the selected elements and some, the majority work on just the first. This all or nothing approach is often exactly what is needed for simple work, but sooner or later you are going to meet a situation where you need to process part of the list of selected elements.

In this case you need to get to know the jQuery result a little better. In fact even if you don't need to process parts of lists of selected elements it is still work knowing more about the nature of the jQuery result.

The basic ideas of the jQuery result object is covered in an earlier chapter Getting Started With jQuery - The DOM.

But it is worth restating the basics here.

When you write

$("p");

which is a shorthand for 

jQuery("p");

the result, in both cases, is a jQuery result object which you can think of as an array, complete with all the jQuery methods you already know. 

The important point is that even if:

$("p");

only matches a single element, the result is still an array - of one element. 

The elements of the jQuery result are DOM elements not jQuery objects in their own right. 

That is:

$("p") 

is a jQuery object, but:

$("p")[0];

is a DOM element, the first in the selection array, and you cannot use any jQuery methods on it. 

 

If you want make use of jQuery methods on one or more of the array elements then the solution is to wrap the DOM element in a jQuery object. That is:

$($("p")[0]);

returns a jQuery object which wraps the first selected paragraph. After this you can do things like

$($("p")[0]).append("<p>Hello</p>");

which would append the new paragraph to the first selected paragraph.

One subtle point, but don't let it confuse you, is that when you wrap a single DOM element you still get a jQuery result array object. 

Filters

Once you have an array of selected elements there is often a need to process all of them in some way. Recall that many jQuery methods simply work on the first array element.

In Getting Started With jQuery - The DOM the array of DOM objects that a selection produced was processed using array indexing and rewrapping.

For example, you could use a for loop to step through each element of a selected set of elements:

var result=$('p');
for(var i=0;i<result.length;i++){
  
$(result[i]).text(i.toString());
}

 

In this case a different number is added to each of the paragraphs.

 

There is a slightly more elegant was of manipulating the jQuery result array. You can apply filters to narrow down the elements that operations apply to. 

You can think of this as a two stage-process of getting the list of elements you actually want to work with. 

The first is to apply a selector to create a result array that consists of all of the DOM elements that match. 

The second is to apply a filter to the result array that selects the element that are to be processed. 

There are generally two ways to write a filter - as part of the selector or as a separate operation.

For example, you can pick out a particular element in the array using either 

.eq(i)

or

:eq(i)

The first is a standard method and the second is a special string that can be included in the selector.

In both cases i is the index of the array element you want and negative indexes are taken to be relative to the end of the array. That is eq(0) is the first element and eq(-1) is the last element. 

That is:

  • selectors extract a set of DOM elements from the DOM as a jQuery array.
  • filters extract a set of elements in a jQuery array as a new jQuery array.

So for example

 $("p").eq(0).append("<p>Hello</p>");

selects all the paragraph elements and returns an array of results, The eq method trims this array down to just the first element and creates a new array containing only it. Then finally the append method adds a new paragraph to just this element. 

The command:

$("p:eq(0)").append("<p>Hello2</p>");

does exactly the same thing but in this case the first call to jQuery, i.e. $("p:eq(0)"), returns the array already trimmed down to a single element. 

Notice that both forms are easier to use than using an array index because: 

 $("p")[0];

is a DOM object rather than a jQuery result array, but:

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

and

$("p:eq(0)");

are jQuery result objects and you don't need to re-wrap them. 

Method v Selector Filters

The difference between the two forms of filter is completely down to where they are applied.

You can use .eq() to repeatedly filter down a result array, to get different elements each time, but :eq returns a single filtered result. 

That is you could do something like

var result=$('p');
for(var i=0;i<result.length;i++){
   
result.eq(i).text(i.toString());
}

To add a string to each of the elements of the result.

While you could use the selector form it would mean having to build up a suitable string and making the query multiple times.

The rule is:

  • use the method form of a filter, e.g. .eq(i) if you need to process an existing array or process an array multiple times

  • use the selector form of a filter, e.g. :eq(i) if you only need to apply the filter once and never need the full unfiltered result. 

There is also another subtle difference between the two forms of the filter. The selector filters are applied before the array is fully constructed i.e. at the time that the DOM is being searched and therefore there can be performance differences. That is they modify the standard CSS selectors rather than filter the array. This also means that some selector filters can do things that method filters can't as we will see. 

Now you might be saying that the selector form of a filter isn't really a filter as defined earlier because it doesn't actually filter down an existing array - it limits the array that is being built. If you want to think of them as separate things then this is fine because at an implementation level they are but they conceptually do the same sort of job. That is you can imagine :eq(i) working by constructing the results array and then dropping every element but the ith element. 

 
justjquery



Last Updated ( Tuesday, 09 August 2016 )