The jQuery() Function

The jQuery() function (a.k.a. $()) is the most important one in the jQuery library. It is heavily overloaded, however, and there are four different ways you can invoke it.

The first and most common way to invoke $() is to pass a CSS selector (a string) to it. When called this way, it returns the set of elements from the current document that match the selector. jQuery supports most of the CSS3 selector syntax, plus some extensions of its own. Complete details of the jQuery selector syntax are in jQuery Selectors. If you pass an element or a jQuery object as the second argument to $(), it returns only matching descendants of the specified element (or elements). This optional second argument value defines the starting point (or points) for the query and is often called the context.

The second way to invoke $() is to pass it an Element, Document, or Window object. Called like this, it simply wraps the element, document, or window in a jQuery object and returns that object, allowing you to use jQuery methods to manipulate the element rather than using raw DOM methods. It is common to see jQuery programs call $(document) or $(this), for example. jQuery objects can represent more than one element in a document, and you can also pass an array of elements to $(). In this case, the returned jQuery object represents the set of elements in your array.

The third way to invoke $() is to pass it a string of HTML text. When you do this, jQuery creates the HTML element (or elements) described by that text and then returns a jQuery object representing those elements. jQuery does not automatically insert the newly created elements into the document, but the jQuery methods described in Chapter 3 allow you to easily insert them where you want them. Note that you cannot pass plain text when you invoke $() in this way, or jQuery will think you are passing a CSS selector. For this style of invocation, the string you pass to $() must include at least one HTML tag with angle brackets.

When invoked in this third way, $() accepts an optional second argument. You can pass a Document object to specify the document with which the elements are to be associated. (If you are creating elements to be inserted into an <iframe>, for example, you’ll need to explicitly specify the document object of that frame.) Or, you can pass an object as the second argument. If you do this, the object properties are assumed to specify the names and values of HTML attributes to be set on the object. But, if the object includes properties with any of the names "css", "html", "text", "width", "height", "offset", "val" or "data", or properties that have the same name as any of the jQuery event-handler registration methods, then jQuery will invoke the method of the same name on the newly created element and pass the property value to it. (Methods like css(), html() and text() are covered below in Chapter 2 and event handler registration methods are in Chapter 4. For example:

var img = $("<img/>",        // Create a new <img> tag
     { src:url,              // with this HTML attribute,
       css: {borderWidth:5}, // this CSS style,
       click: handleClick    // and this event handler.
     }); 

Finally, the fourth way to invoke $() is to pass a function to it. If you do this, the function you pass will be invoked when the document has been loaded and the DOM is ready to be manipulated. It is very common to see jQuery programs written as anonymous functions defined within a call to jQuery():

jQuery(function() { // Invoked when document has loaded
    // All jQuery code goes here
});

You’ll sometimes see $(f) written using the older and more verbose form: $(document).ready(f).

The function you pass to jQuery() will be invoked with the document object as its this value and with the jQuery function as its single argument. This means that you can undefine the global $ function and still use that convenient alias locally with this idiom:

jQuery.noConflict();  // Restore $ to its original state
jQuery(function($) {  
    // Use $ as a local alias for the jQuery object
    // Put all your jQuery code here
});

jQuery triggers functions registered through $() when the “DOMContentLoaded” event is fired, or, in browsers that don’t support that event, when the “load” event is fired. This means that the document will be completely parsed, but that external resources such as images may not be loaded yet. If you pass a function to $() after the DOM is ready, that function will be invoked immediately—before $() returns.

The jQuery library also uses the jQuery() function as its namespace, and defines a number of utility functions and properties under it. The jQuery.noConflict() function mentioned above is one such utility function. Others include jQuery.each() for general-purpose iteration and jQuery.parseJSON() for parsing JSON text. Chapter 7 lists general-purpose utility functions, and other jQuery functions are described throughout this book.

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.