Channels ▼
RSS

JVM Languages

The jQuery Library


The primary characteristic of the jQuery library is its use of CSS selectors to "query" for pieces of the current document object model (DOM). Each query retrieves a collection of DOM references often referred to as a "wrapped set." What to do next? You just call a method on the elements in the collection, and if the result is another jQuery collection, then you can call another method — thus building a chain of calls. But let’s have a look at some of the most important and commonly used methods.

The method each loops through all the elements stored in the jQuery collection and runs a given function on each of them. Here’s an example:

  
$('input[type=text]').each(function(textBox) {
   // Make some changes to the selected input text field
}

The expression first selects all <input> tags in the current DOM in which the type attribute equals "text," and then invokes the specified function on each element. The action to execute on each queried element is written inline. The function prototype is such that the code receives the selected element as input. Note, however, that you can also avoid specifying a formal parameter in the function and use the keyword this in the body of the inline function to reference the current element. The jQuery library ensures that you’ll find the right element behind the expression this.

The function each is one of the most commonly used functions to process the content of a jQuery collection. Generally speaking, there are two main categories of jQuery functions: those that operate on all of the matched elements in the collection; and those that work just on the first element. For example, the addClass and css methods, respectively, add a CSS class and an individual CSS setting to all elements that match the query.

  
$('input[type=text]').addClass('error-state');
$('tr:odd').css('background-color', '#dedede');

The function size, instead, returns the number of elements returned by the query whose references are stored in the collection. You can set attributes using the attr function and set the inner text or HTML of the element using text and html functions.

  
$('a.submit').html('Save and continue');

Note that all these functions, but specifically text, work in a cross-browser manner. As you may know, some browsers use different approaches when it comes to setting the plain text (no formatting) of a tag. For this reason, the text function of jQuery is even more valuable.

Typically, jQuery functions can be used to set values to all matched elements of a query but also to read values from the collection. Let’s have a look at the following code:

  
var src = $('img.galleryImage').attr('src');

The code first selects all <img> elements that have been styled using the galleryImage class. Next, it attempts to pick up the value of the src attribute. In this case, the value stored in the variable is a scalar value and not an array. Put another way, jQuery functions that operate on all matched elements in writing are limited to return values from the first element of the collection.

Another fairly interesting group of jQuery methods is the family of methods to traverse the DOM. You find methods like next, prev, and parent that let you select an HTML element in the neighborhood of the first element of the jQuery collection. Here’s an example:

  
$('input[type=text]').next()
$('input[type=text]').prev()
$('input[type=text]').parent()

The expressness of jQuery doesn’t end here, though. You can also use the following syntax to retrieve the next anchor starting from the current element.

  
$('#section').next('a')

It comes as the last feature in this article on jQuery methods, but method chaining is certainly not the least important of jQuery features — it's actually one of the most compelling. Method chaining consists of concatenating multiple methods, which results in a more compact, and sometimes expressive, syntax.

  
$('#section').next('a').setInnerText('Click');

The trick is that most jQuery methods (basically those that don’t return a scalar value) return another jQuery collection. The returned collection can be the original collection the previous method worked on, or (sometimes) a filtered collection. The chain is virtually endless and will be stopped only when you place a call to a method that returns a scalar value.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video