jQuery for JavaScript

jQuery for JavaScript
jQuery for JavaScript
  • Currently 0 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Rating: 0/5 (0 votes cast)

Thank you for rating!

You have already rated this page, you can only rate it once!

Your rating has been changed, thanks for rating!

Log in or create a user account to rate this page.

When jQuery library for JavaScript was released in January 2006, everyone thought, "another beautiful toy". Choosing CSS-selectors as the basis was, of course, brilliant idea, but the use of transformations chains looked a little bit too complicated, and the library itself, apparently, did not cover every possible scenario. jQuery was regarded only as a temporary solution.

Only a few months later it became obvious that jQuery is a real piece of engineering art. It skillfully covers a fairly wide range of everyday functions, and thus provides a convenient API for extensions, with the help of which you can add any other functionality. Abstractness lies at its core - we are talking about selecting the DOM elements (Document Object Model) - and it gets the best out of it. Most importantly, if you use the library you adhere to a good programming style, also it works well with other parts of the JavaScript code.

Most modern jQuery reviews are intended for designers and inexperienced developers. I'll try to explain why it is also necessary for experienced programmers.


The key to create a good JavaScript code is to carefully manage namespacing. In JavaScript there is only one global namespace (the object window), and many programmers (and even some libraries) unnecessary clog it. Global variables - are pure evil! More cautious developers minimize their intervention into this realm, by using some other methods, such as the modular model. jQuery introduces a single object in the global namespace - the function/object jQuery. Everything else - is either a feature of the jQuery, or a method of the object, returned by the call of the jQuery function.

What can be said about the improvements in the language? Most libraries provide some resemblance of functions like - display, filter, and cut, which, unfortunately, are not present in those JavaScript engines, which are part of most browsers. Some libraries directly extend the built-in JavaScript classes like String and Array, but this is also not completely safe. String.prototype and Array.prototype are independent global namespaces, and adding any extra properties entails the risk of conflicts related to the use of the same variable names in different contexts.

In jQuery, there are a number of functions that extend the possibilities of JavaScript, but each of them is available only as a property of jQuery: jQuery.each, jQuery.extend, jQuery.grep, jQuery.map, jQuery.merge and jQuery.trim. By definition they will not conflict with any other code.

The notorious function $

In fact, jQuery introduces more than one character in the global namespace, there is also $ function: it is used as a shortcut for jQuery. This is done quite gently: if you want back your former function $ (for example, if you have a part of the code based on Prototype), you can call jQuery.noConflict(), to return to the old function $.

If you want to limit the use of the function $ for jQuery without being worried about the collisions with any other use of the global $ function, jQuery documentation suggests the following method:

(function($) {
  // Within the current block, $ belongs to jQuery
  // Gracefully, right?

The widespread use of $ in jQuery is no more than a clever trick. But if we consider it only in the context of jQuery, then this solution seems to be very flexible.

Choosing elements

Every jQuery-operator starts with the selection of one or more nodes in DOM. jQuery selector syntax (internal language of the library) is an interesting hybrid of CSS1,  CSS2, a bit of CSS3, and some XPath and bunch of other extensions. Let's not go into details, but study some examples:

jQuery( 'div.panel' )
// All div with class="panel"
jQuery( 'p#intro' )
// Paragraph with id="intro"
jQuery( 'div#content a:visible' )
// All visible links within div with id="content"
jQuery( 'input[@name=email]' )
// All input strings with name="email"
jQuery( 'table.orders tr:odd' )
// All odd strings in the table with class="orders"
jQuery( 'a[@href^="http://"]' )
// All external links (that begin with http://)
jQuery( 'p[a]' )
// All the paragraphs that contain at least one link

The most interesting of the above are :visible and :odd, which are unique for jQuery. It should also be noted that the attribute selector uses the @ sign, which corresponds more to XPath than CSS2.

The language of the selectors is very rich and very similar to the regular expressions, so that the time to learn it will pay off.

Anything to do with them

Object, which is returned by the jQuery selectors, is quite an interesting beast. It's a set of DOM-elements and behaves a bit like an array: it has property length, its elements can be accessed by index and (most importantly) Firebug sees it as an array when displayed in its console. This is nothing more than a beautiful illusion: in fact, it's a set of elements - it's a jQuery object, that has a large number of methods for selecting, changing or extending the current set.

In jQuery, there are three different method categories: the first can work with all the elements that match the pattern, the second returns the value of the first found element, and the third alters the selection itself.

We will not list all the possible ways (you can find them at the visualjquery.com), instead we'll give some examples. If you have Firebug, you can try it out yourself: just use the tab "Insert jQuery" (javascript:void(function(){var s=document.createElement('script');s.src='http://code.jquery.com/jquery-1.1.2.js'; document.getElementsByTagName('head')[0].appendChild(s);}())) to load the library for any page, and then paste these code examples into the Firebug console (note: possible even without Firebug: just download jQuery using the link and call these examples in your browser's address bar, don't forget to put at beginning some JavaScript: and maybe some alert at end (so that the page would not display the return value)).

jQuery( 'div#primary' ).width( 300 );
// Sets the width div id = "primary" in 300 pixels.
jQuery( 'p' ).css( 'line-height', '1.8em' );
// Sets the line height to 1.8 em for all paragraphs.
jQuery( 'li:odd' ).css({ color: 'white', backgroundColor: 'black' });
// Uses 2 CSS-rules for each of the items in the list, note that the function css() can have an object of the style sheets instead of the two lines.
jQuery( 'a[@href^="http://"]' ).addClass( 'external' ).attr( 'target', '_blank' );
// Adds class "external" to all external links (those that begin with http://), then adds the target="_blank", to make the difference even greater. This example uses call chains, described below.
jQuery( 'blockquote' ).each(function(el) { alert(jQuery(this).text()) });
// For each blockquote tag, on the page displays a message (alert) with its text content (including HTML-tags).
jQuery( 'a' ).html( 'Click here!' );
// Replaces all the text in the links on the page with a request "Click here!".
// Here are some examples of methods that return the value of the first element, found by the pattern:
var width = jQuery( 'div' ).width();
// What is the width of the first div on the page?
var src = jQuery( 'img' ).attr( 'src' );
// What is the value of the src attribute of the first picture on the page?
var color = jQuery( 'h1' ).css( 'color' );
// What’s the color of the first h1?

Note the convenient symmetry of these methods: they are used to set attributes (when taking 2 arguments or taking a number of properties of the transmitted object), and also to read the values of these attributes (if only one argument is transmitted). This symmetry is used everywhere in jQuery, which greatly helps to memorize API.

Also, there are several methods that change the whole set of the found elements. Many of them also provide moving up and down the DOM-tree:

jQuery( 'div' ).not( '[@id]' )
// Returns all the div’s, which do not have the attribute id.
jQuery( 'h2' ).parent()
// Returns all the elements that are direct parents of h2.
jQuery( 'blockquote' ).children()
// Returns all the elements within the blockquote.
jQuery( 'p' ).eq( 4 ).next()
// Finds the fifth paragraph on the page, then finds the next element (that is, the neighbor to the right.)
jQuery( 'input:text:first' ).parents( 'form' )
// Finds the parent element for the form, which contains the field input type="text" as first on the page. The optional parameter instead of parents() is another selector.

Chain calls

JQuery developers are often proud that their library supports chain calls, you can hear statements like "jQuery was created in order to change your style of programming in JavaScript" and this is written right on the main page. This technique is more like a side branch than the road to the future, but you can use jQuery to avoid long strings of calls.

Call chains can be used for some interesting tricks. In addition to using a set of DOM-samples you can use jQuery method end to move up in the stack of objects, and to exit from the current context. It's a bit hard to explain, but when you use the method that changes the current (object's) context (for example, children or filter), you can use the end a bit later to return to the previous sample. Jesse Skinner gives a good example of using this feature in his workbook: "Simplify Ajax development with jQuery":

$( 'form#login' )
  // hiding inside the form all the labels with the class optional
  .find( 'label.optional' ).hide().end()
  // add a red border to all password-like fields in the form
  .find( 'input:password' ).css( 'border', '1px solid red' ).end()
  // add an event handler submit for the form 
    return confirm( 'Are you sure you want to send the data?' );

All this amazing transformation takes only one string. It finds the form, some elements within it, applies the changes, returns back to the form and adds the event handler submit to the form.

Manipulate the DOM

In jQuery, there are several ways to manipulate the DOM in a bulk. The first one is a bit of an unexpected surprise: the jQuery function can take as an argument a piece of HTML-code, which is converted into a DOM-element (in fact, it's a simple string):

var div = jQuery( 'Some text' );

You can use the chain calls to add attributes to div, as soon as it has been created:

var div = jQuery( '<div>Some text</div>' ).addClass( 'inserted' ).attr( 'id', 'foo' );
// Now let's add var div = jQuery( '<div>Some text</div>' ).addClass( 'inserted' ).attr( 'id', 'foo' ); it to the tag body:
div.appendTo( document.body )
// Or insert it, using the selector, in the existing code:
div.prependTo( 'div#primary' )

Intercepting events

All JavaScript libraries need methods to handle events, and jQuery is no exception. As in the case of attr and css, methods for the events can serve two purposes: their call with the function as an argument assigns the event handler, a call without an arguments emulates this event:

jQuery( 'p' ).click(function() { jQuery( this ).css( 'background-color', 'red' ); });
// Set for all paragraphs a mouse click handler according to which they turn red.
jQuery( 'p:first' ).click()
// Emulates a click to the first paragraph on the page.
// Similar functions are used for other browser events: mouseover, keyup etc. Note that when you call the event handler, the keyword this refers to the element that caused the event, the use of jQuery( this ) is a conventional way to call jQuery methods for this element.
// A couple of functions related to events deserve special attention:
jQuery( 'a' ).hover(function() {
  jQuery( this ).css( 'background-color', 'orange' );
}, function() {
  jQuery( this ).css( 'background-color', 'white' );
// hover() is a shortcut for two events: onmouseover and onmouseout.
jQuery( 'p' ).one( 'click', function() { alert( jQuery(this).html() ); });
// one () sets an event handler that will be removed after its first call. In the example above, all paragraphs should show (alert) their contents after the first click on them.
// jQuery also supports its own events with the help of methods like bind() and trigger() (similar to click()). Own events can take arguments passed by the array in the call of trigger():
jQuery( document ).bind( 'stuffHappened', function( event, msg ) {
  alert( 'What happened: ' + msg );
jQuery( document ).trigger( 'stuffHappened', ['Hello!'] );

Unobtrusive programming

Best Web applications - are those that can function with disconnected scripts, and the best method to achieve this would be the unobtrusive JavaScript, when the events are assigned to elements only after the whole HTML-page has loaded (for more information, see unobtrusive programming and Hijax).

jQuery has excellent support of this approach. First, the paradigm of the selectors to select nodes is fundamental for jQuery, as well as for the unobtrusive programming in general. Second, jQuery provides solutions to the problem window.onload, based on the research of Dean Edwards concerning the operation of the event "DOM loaded" for different browsers. You can set the handler function to operate when the DOM is already ready for it:

jQuery( document ).ready(function() {
  alert( 'DOM ready!' );

You can do even more, you can make this record shorter, by assigning your function directly to jQuery():

jQuery(function() {
  alert( 'DOM ready!' );

jQuery and AJAX

jQuery is the best API for working with AJAX, I've ever seen among other large libraries. The most simple form of AJAX-call looks the following way:

jQuery( 'div#intro' ).load( '/some/fragment.html' );

It will execute GET-request to /some/fragment.html and insert the returned HTML-code into div#intro.

But what if you need something more complex, for example to display AJAX-loading? jQuery provides a set of its own events (ajaxStart, ajaxComplete, ajaxError and others) which are used when necessary. Also this library has a more advanced low-level API for complex AJAX-interactions:

jQuery.get( '/some/script.php', { 'name': 'Simon' }, function( data ) {
  alert( 'The server responded: ' + data );
}); // GET-request to /some/script.php?name=Simon

jQuery.post( '/some/script.php', { 'name': 'Simon' }, function( data ) {
  alert( 'The server responded: ' + data );
}); // POST-request to /some/script.php

jQuery.getJSON( '/some.json', function( json ) {
  alert( 'JSON returned: ' + json.foo + ' ' + json.bar );
}); // Returns and changes the response from /some.json to JSON

jQuery.getScript( '/script.js' ); // GET-request to /script.js and eval()


If counting the whole set of standard features, it is worth noting that abridge version of jQuery has only 20 KB, and even less if you use archive (.gz). Additional functionality that extends beyond the standard version can be achieved with the help of extensions that can (and do) add new methods to the existing jQuery object. If you want, you can do something like this:

jQuery( 'p' ).bounceAroundTheScreenAndTurnGreen();

The extension mechanism in jQuery provides documented methods for adding them to the system. Simplicity of use has attracted a large community of authors of such extensions, the extensions directory has more than a hundred examples.

One more pleasant feature is the ability to add your own selectors as well as your own methods. The extension moreSelectors adds methods like div:color(red), which, for example, selects all div's with red text.


This article gave enough evidence for a positive conclusion about jQuery, that it's not just another library. It contains a lot of interesting ideas that can surprise even the most experienced JavaScript programmers - and teach them something new. Even if you are not going to use it in your work, it is worth to devote some of your time and explore the "ecosystem" named jQuery.

Read also

jQuery for beginners: selectors

jQuery for beginners: selectors

jQuery for beginners: AJAX

jQuery for beginners: AJAX

jQuery UI. Widgets. Dialog (Windows)

jQuery UI. Widgets. Dialog (Windows)

jQuery UI. Widgets. Datepicker (Calendar)

jQuery UI. Widgets. Datepicker (Calendar)

Log in or create a user account to post a comment.


Quick navigation

General navigation