jQuery Basics


jQuery is a JavaScript* library designed to simplify script interactions with the DOM. It provides a cross-platform API that masks the differences between the various web runtime APIs and provides an easy-to-use framework for developing unobtrusive JavaScript.

At the heart of jQuery is the Sizzle selector engine. To promote clean separation of JavaScript code from HTML markup, jQuery selectors enable you to easily retrieve desired elements from the DOM on which to perform operations, rather than having to embed operations within the HTML elements themselves.

The typical syntax for a jQuery operation is:

$('selector').method();

The main jQuery() function, or simply $() for shorthand, accepts a selector string expression, and returns a jQuery object that contains a collection of matched DOM elements. jQuery provides many document traversing, event handling, Ajax, DOM and CSS manipulation, and animation methods that can be applied to each of the matching DOM elements that are returned by a query. Alternatively, a custom function can be mapped to the collection using the each() method. Most of these methods return the original collection of matched elements, so multiple operations can be "chained" together, producing very efficient and compact code:

/* chained */
$('selector')
    .method1()
    .method2()
    .method3();
/* unchained */
$('selector').method1();
$('selector').method2();
$('selector').method3();

jQuery also provides filtering methods that reduce a collection of matched elements to a list that meet the filter criteria. These methods return a new jQuery object containing the filtered subset of element(s), which can then be operated on by additional jQuery methods.

Finally, jQuery provides a $(document).ready() event so that your code can run as soon as the DOM has been fully constructed and is ready to be processed. Compared with the standard load event, the ready event does not have to wait for all assets to be downloaded and the page to be fully rendered in order to trigger.

For additional information on jQuery, check out these great overviews:

Also keep in mind that jQuery was originally designed to facilitate the addition of dynamic behavior to relatively simple web pages. As you build larger apps, with more complex behavior, think hard about how to organize your jQuery code so it is readable and extensible.

For more complete information about compiler optimizations, see our Optimization Notice.
Categories: