jQuery Selectors and Filters

jquery

jQuery is the most popular open source JavaScript Library in the world. It simplifies the task of making highly responsive web pages that work across all of the modern web browsers. jQuery makes common scripting tasks much easier by providing a short and easy to understand syntax. Instead of having to access the DOM directly, jQuery provides a much easier way to access, modify, and update the DOM as you see fit. jQuery is used everywhere, and we need to be fluent in it as well so lets jump right in to jQuery!


jQuery Overview

jQuery breaks down into several categories of functionality. They are listed as follows:

  • Core Functionality Provides the core features of the library as well as many helpful utility methods.
  • Selection and Traversal This provides the common functions for finding what you want inside of HTML documents, as well as the traversal of those documents.
  • Manipulation and CSS Functions in this category allow for editing and changing the content within the document as well as manipulating CSS.
  • Events jQuery provides a powerful unified event object that simplifies working with events and cross browser event related problems.
  • Effects As you have surely seen on the web, jQuery is the library that can provide animations, hiding and showing of content, as well as moving elements on the page.
  • Ajax One of the most powerful aspects of the library is its excellent implementation of AJAX and the related helper methods that come along with this.

jQuery Selectors and Filters

The journey you take with jQuery begins with the selectors available to you. The first thing you usually do before anything else in jQuery is to select some elements from a web page so that you can do something with them. By using selectors, and optionally filters, you can be very precise in selecting data to work on. This is the ‘Query’ part of jQuery. Just as you would query a database in PHP, so to would you query a web page or document in jQuery to get data to work with.

  • jQuery selectors return an array of objects based on the criteria given for the selector.
  • jQuery filters on the other hand, refine the results contained in the returned array.

The returned array is not a set of DOM elements. What gets returned are actually jQuery objects, or DOM elements wrapped within jQuery objects. It is this wrapping that provides all of the methods and properties that jQuery has to offer so you can operate on those selected objects. This is often called the wrapped set.


Making Use of Basic jQuery Selectors

jQuery selectors are based on the familiar CSS selector syntax. They work in a very similar way. The following table shows a summary of basic jQuery selectors. These are a good starting point and should be memorized. The selector expression is what goes inside of the $('selector') jQuery function. Almost all jQuery statements will begin with some form of selection.

Selector

Use Case

tagname select all elements with the given tagname
#identifier select all elements with the ID of identifier
.className select all elements that have a class attribute set to className
tag.className select all elements for the provided tag which have a class attribute set to className
tag#wow.className select all elements that have an ID set to wow and a class set to className
* get all elements on the page.

Using the DOM vs using jQuery

Let’s look at some examples of how to select data from a document using the DOM and native JavaScript, vs using jQuery. It is useful to compare the two approaches for two reasons. First, you can appreciate the syntax of jQuery and second, you need to get an idea of what jQuery is doing under the hood when you make use of the built in methods.

We’ll use this example HTML to test some of these basic selectors.

Select every <p> tag

native: document.getElementsByTagName('p');
jQuery: $('p');

Select the tag with ID of funlist

native: document.getElementById('funlist');
jQuery: $('#funlist');

Get all <li> tags with a class of markup

jQuery: $('li.markup');

Get all tags with a class of presentation, but only if they are inside of a <ul>
jQuery: $('ul .presentation');

On the last two examples we skip the native JavaScript code since it requires some complex logic and looping within the script to complete. This is where the power of jQuery starts to come through. In fact if you use jQuery for nothing other than a selector engine, you have saved yourself a great deal of time and frustration.


Combination and Hierarchy jQuery Selectors

The combination and hierarchy selectors are slightly more advanced than the basic selectors described above. These will give you a more advanced and granular way of selecting content from the page. With these selectors, you can get elements based on a series of common criteria, or by a hierarchical relationship. The following table give an overview of these types of selectors.

Combination

Selector

Use Case

p, li select all p tags and all li tags
.class1.class2 get all elements that have both class1 and class2

Hierarchy

Selector

Use Case

parent > child get all child elements that are direct children of elements of type parent
ancestor descendant get all descendant elements that are within elements of the ancestor type

Siblings

Selector

Use Case

prev + next get all next elements that are next to a prev element
prev ~ siblings get all sibling elements that are after prev and match the siblings selector

These are a little more tricky so let’s take a look at some examples. You’ll see in the example HTML provided that we also included a copy of Twitter Bootstrap in the page. This way, we can make use of the jQuery .addClass() method and simply add a class to our selected elements. The traditional tutorial might use the jQuery .css() method and pass in some CSS values, and this is a perfectly good way to show selecting elements as well. We’ll load up the HTML in a web browser and run the following commands in firebug to see what happens. For the entirety of this post, we can focus on the initial part of the expression, meaning, anything that comes before .addClass().

jquery selectors

This is pretty cool! By loading up our jQuery enabled page in firefox with firebug running, we can simply type some simple jQuery into the console of firebug and trigger off page updates in real time. You don’t have to stop there, refresh your browser to clear the styling, and click the clear button in the firebug console to clear out your sample jQuery. Now you can go crazy testing any combination of selectors you can think of! You should do just that as well – by practicing all of the different combinations of selectors on your markup, you’ll quickly become familiar with how these selectors work and after a while they will become second nature to you.


Using jQuery Filters

Filters work with selectors. Think of them as a way to make your selectors more granular. By combining filters with your selectors, you can grab any thing on the page at any point with a high level of precision. jQuery Filters fall into the following categories.

  • Basic Basic filters allow you to filter the first, last, even, or odd numbered items from the wrapped set.
  • Content Content filters provide the ability to filter elements based on the content such as an element containing a given string.
  • Visibility Filters the set of elements by looking at the visibility setting of each element.
  • Attribute Looks at a provided attribute an an element to filter out or not.
  • Child Gets elements depending on their relationship with their parent element.
  • Form Gives filters to specifically operate on form elements in the page.

Here are some of the most commonly used filters. In looking at them, we can see how they are essentially CSS selectors, and they work much the same. The syntax is very similar.

Filter

Use Case

:first Selects the first instance of the wrapped set
:last Selects the last instance of the wrapped set
:even Returns only even numbered elements
:odd Returns only odd numbered elements
:eq(n) Returns only the index provided
:gt(n) Includes elements that are past the index given
:lt(n) Includes elements that are before the index given
:header Selects all header elements like h1, h2, h3, h4
:animated Selects elements that are animated in some way
:not(selector) Includes elements that don’t match the given selector

So where would you use filters? Well consider a scenario where there are a lot of elements on the page, and maybe there are not a lot of unique ID’s in use or class names for that matter. In selecting data, we need some way to identify it. If we are unable to narrow things down with basic selectors, we then start using filters to refine things. Let’s see some of these filters in action operating on the same HTML we used for the selectors examples.

jquery filters

In fact as we use jQuery, just like in native JavaScript or another programming language, there are often several paths to the final destination. You can solve the same problem with many different approaches. How you solve that problem is a matter of preference and style, and we know you are one stylish person!


jQuery Attribute Filters

In addition to the positional and index based filters we mentioned so far, jQuery also provides a great set of attribute filters. What this does is allow us to filter the results of a selector statement based on the content of an attribute. Here are the attribute filters to know.

Filter

Use Case

[attribute] Includes elements in the result set if they have the given attribute
[attribute=value] Includes elements in the result set only if they have the given attribute and a specific value
[attribute!=value] Includes elements in the result set only if they have the given attribute and it is not a specific value
[attribute^=value] Includes elements in the result set only if they have the given attribute and it starts with the given value
[attribute$=value] Includes elements in the result set only if they have the given attribute and it ends with the given value
[attribute*=value] Includes elements in the result set only if they have the given attribute and it contains a specific value
[attr1][attr2] Includes elements in the result set only if they match all given attribute filters

Making use of the different types of attribute filters, we can see how they behave. Attribute filters come in really handy quite often.

jquery attribute filters


jQuery Content and Visibility Filters

Moving on in our study of filters in jQuery, we now will take a look at content and visibility filters. You may have thought there were no additional filters to need, but alas, jQuery gives you virtually limitless options when it comes to selecting and filtering data.

Filter

Use Case

:contains(text) Filters the selection to include elements that contain text string
:empty Filters the selection to only include elements that are empty
:has(selector) Will match elements that contain at least one element which has the given selector
:parent Matches all elements that have at least one child element
:visible Filters the wrapped set to only visible elements
:hidden Filters the wrapped set to only hidden elements

jQuery Child Filters

jQuery also provides several child filters. This table shows a collection of child filters from jQuery.

Filter

Use Case

:nth-child(index)
:nth-child(even)
:nth-child(odd)
:nth-child(equation)
Matches elements at the index, even, odd, or that match an equaltion in the form of Xn + M.
:first-child Matches elements that are the first child of their parent element
:last-child Matches elements that are the last child of their parent element
:only-child Matches elements that are the only child of their parent element

As with the other examples, simply think of creative ways to test these filters in the browser using firebug and some test HTML. Practice makes Perfect!


jQuery Form Selectors

jQuery also has many types of form selectors. Their syntax may seem a little confusing as they actually look like filters since they start with the colon : operator. Usually when we see this operator, we know we are doing some type of filtering. In the case of Forms in jQuery, it is for selection.

Selector

Use Case

:input Finds all input, select, textarea, and button elements
:text Finds all text elements
:password Finds all password elements
:radio Finds all radio buttons
:checkbox Finds all checkboxes
:submit Finds all submit elements
:reset Finds all reset elements
:image Finds all images
:button Finds all buttons
:file Finds all file upload elements
:enabled Finds all enabled form elements
:disabled Finds all disabled form elements
:checked Finds all form elements that are checked
:selected Finds all form elements that are selected

Conclusion

This completes the study of jQuery selectors and filters for this tutorial. It may seem a bit long, but in reality, when we are using jQuery as we have stated earlier on, the very first thing you do in jQuery is to select content from the page to operate on. It makes sense to have your selectors and filters down cold, since if you have the right data to work with to begin with, your applications will be that much easier to build and debug. Take some time to test these out. It’s as easy as opening the firebug console and typing some example selector and filter statements in!