Queries and Query Results

When you pass a jQuery selector string to $(), it returns a jQuery object that represents the set of matched (or “selected”) elements. jQuery selectors are very much like the CSS selectors you use in stylesheets. For example:

div            // all <div> elements
#surname       // the element with id="surname"
.warning       // all elements with class="warning"

The specific selector syntax supported by jQuery is detailed in jQuery Selectors. Rather than focus on those advanced selector details now, we’re going to first explore what you can do with the results of a query.

The value returned by $() is a jQuery object. jQuery objects are array-like: they have a length property and numeric properties from 0 to length-1. This means that you can access the contents of the jQuery object using standard square-bracket array notation:

$("body").length  // => 1: documents have only one body
$("body")[0]      // This the same as document.body

If you prefer not to use array notation with jQuery objects, you can use the size() method instead of the length property, and the get() method instead of indexing with square brackets. If you need to convert a jQuery object to a true array, call the toArray() method.

In addition to the length property, jQuery objects have three other properties that are sometimes of interest. The selector property is the selector string (if any) that was used when the jQuery object was created. The context property is the context object that was passed as the second argument to $(), or the Document object otherwise. Finally, all jQuery objects have a property named jquery, and testing for the existence of this property is a simple way to distinguish jQuery objects from other array-like objects. The value of the jquery property is the jQuery version number as a string:

// Find all <script> elements in the document body
var bodyscripts = $("script", document.body);
bodyscripts.selector   // => "script"
bodyscripts.context    // => document.body
bodyscripts.jquery     // => "1.4.2"

If you want to loop over all elements in a jQuery object, call the each() method instead of writing a for loop. The each() method is something like the ECMAScript 5 (ES5) forEach() array method. It expects a callback function as its sole argument, and invokes that callback function once for each element in the jQuery object (in document order). The callback is invoked as a method of the matched element, so within the callback the this keyword refers to an Element object. each() also passes the index and the element as the first and second arguments to the callback. Note that this and the second argument are raw document elements, not jQuery objects; if you want to use a jQuery method to manipulate the element, you’ll need to pass it to $() first.

jQuery’s each() method has one feature that is quite different than forEach(): if your callback returns false for any element, iteration is terminated after that element (this is like using the break keyword in a normal loop). each() returns the jQuery object on which it is called so that it can be used in method chains. Here is an example (it uses the prepend() method that will be explained in Chapter 3):

// Number the divs of the document, up to div#last
$("div").each(function(idx) { // Invoke for each <div>
    // Create a jQuery object from the element
    // And insert the index at start of it.
    $(this).prepend(idx + ": ");  
    // Stop iterating when we reach #last
    if (this.id === "last") 
        return false;
});

Despite the power of the each() method, it is not very commonly used since jQuery methods usually iterate implicitly over the set of matched elements and operate on them all. You typically only need to use each() if you need to manipulate the matched elements in different ways. Even then, you may not need to call each() since a number of jQuery methods allow you to pass a callback function.

The jQuery library predates the ES5 array methods and defines a couple of other methods that provide similar functionality. The jQuery method map() works much like the Array.map() method. It accepts a callback function as its argument and invokes that function once for each element of the jQuery object, collecting the return values of those invocations, and returning a new jQuery object holding those return values. map() invokes the callback in the same way as the each() method: the element is passed as the this value and as the second argument, and the index of the element is passed as the first argument. If the callback returns null or undefined, that value is ignored and nothing is added to the new jQuery object for that invocation. If the callback returns an array or an array-like object (such as a jQuery object), it is “flattened” and its elements are added individually to the new jQuery object. Note that the jQuery object returned by map() may not hold document elements, but it still works as an array-like object. Here is an example:

$(":header")                // Find all headings.
    .map(function() {       // Map them to
            return this.id; // their ids.
         })
    .toArray()              // Convert to a true array
    .sort();                // And sort that array

Along with each() and map(), another fundamental jQuery method is index(). This method expects an element as its argument, and it returns the index of that element in the jQuery object, or -1 if it is not found. In typical jQuery fashion, however, this index() method is overloaded. If you pass a jQuery object as the argument, index() searches for the first element of that object. If you pass a string, index() uses it as a CSS selector and returns the index of the first element of this jQuery object in the set of elements matching that selector. And if you pass no argument, index() returns the index of the first element within its sibling elements.

The final general-purpose jQuery method we’ll discuss here is is(). It takes a selector as its argument and returns true if at least one of the selected elements also matches the specified selector. You might use it in an each() callback function, for example:

$("div").each(function() {     // For each <div> element
    if ($(this).is(":hidden")) // Skip hidden elements
        return;
    // Do something with the visible ones here
});

Get jQuery Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.