Chapter 1. jQuery Basics

Cody Lindley

Introduction

Since you’ve picked up a cookbook about jQuery, the authors of this book for the most part are going to assume that you have a loose idea about what exactly jQuery is and what it does. Frankly, cookbooks in general are typically written for an audience who seeks to enhance a foundation of knowledge that has already been established. Thus, the recipe-solution-discussion format is used to quickly get you solutions to common problems. However, if you are a jQuery newbie, don’t throw this book against the wall and curse us just yet. We’ve dedicated this chapter to you.

If you are in need of a review or are jumping into this cookbook with little or no working knowledge of jQuery, this first chapter alone (the other chapters assume you know the basics) will aid you in learning the jQuery essentials. Now, realistically, if you have absolutely zero knowledge of JavaScript and the DOM, you might want to take a step back and ask yourself whether approaching jQuery without a basic understanding of the JavaScript core language and its relationship with the DOM is plausible. It would be my recommendation to study up on the DOM and JavaScript core before approaching jQuery. I highly recommend JavaScript: The Definitive Guide by David Flanagan (O’Reilly) as a primer before reading this book. But don’t let my humble opinion stop you if you are attempting to learn jQuery before you learn about the DOM and JavaScript. Many have come to a working knowledge of these technologies by way of jQuery. And while not ideal, let’s face it, it can still be done.

With that said, let’s take a look at a formal definition of jQuery and a brief description of its functionality:

jQuery is an open source JavaScript library that simplifies the interactions between an HTML document, or more precisely the Document Object Model (aka the DOM), and JavaScript.

In plain words, and for the old-school JavaScript hackers out there, jQuery makes Dynamic HTML (DHTML) dead easy. Specifically, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development.

With a formal explanation of jQuery under our belts, let’s next explore why you might choose to use jQuery.

Why jQuery?

It might seem a bit silly to speak about the merits of jQuery within this cookbook, especially since you’re reading this cookbook and are likely already aware of the merits.

So, while I might be preaching to the choir here, we’re going to take a quick look at why a developer might choose to use jQuery. My point in doing this is to foster your basic knowledge of jQuery by first explaining the “why” before we look at the “how.”

In building a case for jQuery, I’m not going to compare jQuery to its competitors in order to elevate jQuery’s significance. That’s because I just don’t believe that there really is a direct competitor. Also, I believe the only library available today that meets the needs of both designer types and programmer types is jQuery. In this context, jQuery is in a class of its own.

Of the notorious JavaScript libraries and frameworks in the wild, I truly believe each has its own niche and value. A broad comparison is silly, but it’s nevertheless attempted all the time. Heck, I am even guilty of it myself. However, after much thought on the topic, I truly believe that all JavaScript libraries are good at something. They all have value. What makes one more valuable than the other depends more upon who is using it and how it’s being used than what it actually does. Besides, it has been my observation that micro differences across JavaScript libraries are often trivial in consideration of the broader goals of JavaScript development. So, without further philosophical ramblings, here is a list of attributes that builds a case for why you should use jQuery:

  • It’s open source, and the project is licensed under an MIT and a GNU General Public License (GPL) license. It’s free, yo, in multiple ways!

  • It’s small (18 KB minified) and gzipped (114 KB, uncompressed).

  • It’s incredibly popular, which is to say it has a large community of users and a healthy amount of contributors who participate as developers and evangelists.

  • It normalizes the differences between web browsers so that you don’t have to.

  • It’s intentionally a lightweight footprint with a simple yet clever plugin architecture.

  • Its repository of plugins is vast and has seen steady growth since jQuery’s release.

  • Its API is fully documented, including inline code examples, which in the world of JavaScript libraries is a luxury. Heck, any documentation at all was a luxury for years.

  • It’s friendly, which is to say it provides helpful ways to avoid conflicts with other JavaScript libraries.

  • Its community support is actually fairly useful, including several mailing lists, IRC channels, and a freakishly insane amount of tutorials, articles, and blog posts from the jQuery community.

  • It’s openly developed, which means anyone can contribute bug fixes, enhancements, and development help.

  • Its development is steady and consistent, which is to say the development team is not afraid of releasing updates.

  • Its adoption by large organizations has and will continue to breed longevity and stability (e.g., Microsoft, Dell, Bank of America, Digg, CBS, Netflix).

  • It’s incorporating specifications from the W3C before the browsers do. As an example, jQuery supports a good majority of the CSS3 selectors.

  • It’s currently tested and optimized for development on modern browsers (Chrome 1, Chrome Nightly, IE 6, IE 7, IE 8, Opera 9.6, Safari 3.2, WebKit Nightly, Firefox 2, Firefox 3, Firefox Nightly).

  • It’s downright powerful in the hands of designer types as well as programmers. jQuery does not discriminate.

  • Its elegance, methodologies, and philosophy of changing the way JavaScript is written is becoming a standard in and of itself. Consider just how many other solutions have borrowed the selector and chaining patterns.

  • Its unexplainable by-product of feel-good programming is contagious and certainly unavoidable; even the critics seem to fall in love with aspects of jQuery.

  • Its documentation has many outlets (e.g., API browser, dashboard apps, cheat sheets) including an offline API browser (AIR application).

  • It’s purposely bent to facilitate unobtrusive JavaScript practices.

  • It has remained a JavaScript library (as opposed to a framework) at heart while at the same time providing a sister project for user interface widgets and application development (jQuery UI).

  • Its learning curve is approachable because it builds upon concepts that most developers and designers already understand (e.g., CSS and HTML).

It is my opinion that the combination of the aforementioned jQuery points, and not any single attribute on its own, sets it apart from all other solutions. The total jQuery package is simply unmatched as a JavaScript tool.

The jQuery Philosophy

The jQuery philosophy is “Write less, do more.” This philosophy can be further broken down into three concepts:

  • Finding some elements (via CSS selectors) and doing something with them (via jQuery methods)

  • Chaining multiple jQuery methods on a set of elements

  • Using the jQuery wrapper and implicit iteration

Understanding these three concepts in detail is foundational when it comes time to write your own jQuery code or augment the recipes found in this book. Let’s examine each of these concepts in detail.

Find some elements and do something with them

Or more specifically stated, locate a set of elements in the DOM, and then do something with that set of elements. For example, let’s examine a scenario where you want to hide a <div> from the user, load some new text content into the hidden <div>, change an attribute of the selected <div>, and then finally make the hidden <div> visible again.

This last sentence translated into jQuery code would look something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div>old content</div>
<script>

//hide all divs on the page
jQuery('div').hide();

//update the text contained inside of all divs
jQuery('div').text('new content');

//add a class attribute with a value of updatedContent to all divs
jQuery('div').addClass("updatedContent");

//show all divs on the page
jQuery('div').show();

</script>
</body>
</html>

Let’s step through these four jQuery statements:

  • Hide the <div> element on the page so it’s hidden from the user’s view.

  • Replace the text inside the hidden <div> with some new text (new content).

  • Update the <div> element with a new attribute (class) and value (updatedContent).

  • Show the <div> element on the page so it’s visible again to the viewing user.

If the jQuery code at this point is mystical syntax to you, that’s OK. We’ll dive into the basics with the first recipe in this chapter. Again, what you need to take away from this code example is the jQuery concept of “find some elements and do something with them.” In our code example, we found all the <div> elements in the HTML page using the jQuery function (jQuery()), and then using jQuery methods we did something with them (e.g., hide(), text(), addClass(), show()).

Chaining

jQuery is constructed in a manner that will allow jQuery methods to be chained. For example, why not find an element once and then chain operations onto that element? Our former code example demonstrating the “Find some elements and do something with them” concept could be rewritten to a single JavaScript statement using chaining.

This code, using chaining, can be changed from this:

//hide all divs on the page
jQuery('div').hide();

//update the text contained inside of the div
jQuery('div').text('new content');

//add a class attribute with a value of updatedContent to all divs
jQuery('div').addClass("updatedContent");

//show all divs on the page
jQuery('div').show();

to this:

jQuery('div').hide().text('new content').addClass("updatedContent").show();

or, with indenting and line breaks, to this:

jQuery('div')
    .hide()
    .text('new content')
    .addClass("updatedContent")
    .show();

Plainly speaking, chaining simply allows you to apply an endless chain of jQuery methods on the elements that are currently selected (currently wrapped with jQuery functionality) using the jQuery function. Behind the scenes, the elements previously selected before a jQuery method was applied are always returned so that the chain can continue. As you will see in future recipes, plugins are also constructed in this manner (returning wrapped elements) so that using a plugin does not break the chain.

If it’s not immediately obvious, and based on the code in question, chaining also cuts down on processing overhead by selecting a set of DOM elements only once, to then be operated on numerous times by jQuery methods by way of chaining. Avoiding unnecessary DOM traversing is a critical part of page performance enhancements. Whenever possible, reuse or cache a set of selected DOM elements.

The jQuery wrapper set

A good majority of the time, if jQuery is involved, you’re going to be getting what is known as a wrapper. In other words, you’ll be selecting DOM elements from an HTML page that will be wrapped with jQuery functionality. Personally, I often refer to this as a “wrapper set” or “wrapped set” because it’s a set of elements wrapped with jQuery functionality. Sometimes this wrapper set will contain one DOM element; other times it will contain several. There are even cases where the wrapper set will contain no elements. In these situations, the methods/properties that jQuery provides will fail silently if methods are called on an empty wrapper set, which can be handy in avoiding unneeded if statements.

Now, based on the code we used to demonstrate the “Find some elements and do something with them” concept, what do you think would happen if we added multiple <div> elements to the web page? In the following updated code example, I have added three additional <div> elements to the HTML page, for a total of four <div> elements:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/
jquery/1.3.0/jquery.min.js"></script> </head>
<body>
<div>old content</div>
<div>old content</div>
<div>old content</div>
<div>old content</div>
<script>
//hide all divs on the page
jQuery('div').hide().text('new content').addClass("updatedContent").show();

</script>
</body>
</html>

You may not have explicitly written any programmatic loops here, but guess what? jQuery is going to scan the page and place all <div> elements in the wrapper set so that the jQuery methods I am using here are performed (aka implicit iteration) on each DOM element in the set. For example, the .hide() method actually applies to each element in the set. So if you look at our code again, you will see that each method that we use will be applied to each <div> element on the page. It’s as if you had written a loop here to invoke each jQuery method on each DOM element. The updated code example will result in each <div> in the page being hidden, filled with updated text, given a new class value, and then made visible again.

Wrapping your head around (pun intended) the wrapper set and its default looping system (aka implicit iteration) is critical for building advanced concepts around looping. Just keep in mind that a simple loop is occurring here before you actually do any additional looping (e.g., jQuery('div').each(function(){}). Or another way to look at this is each element in the wrapper will typically be changed by the jQuery method(s) that are called.

Something to keep in mind here is there are scenarios that you will learn about in the coming chapters where only the first element, and not all the elements in the wrapper set, is affected by the jQuery method (e.g., attr()).

How the jQuery API Is Organized

There is no question that when I first started out with jQuery, my main reason for selecting it as my JavaScript library was simply that it had been properly documented (and the gazillion plugins!). Later, I realized another factor that cemented my love affair with jQuery was the fact that the API was organized into logical categories. Just by looking at how the API was organized, I could narrow down the functionality I needed.

Before you really get started with jQuery, I suggest visiting the documentation online and simply digesting how the API is organized. By understanding how the API is organized, you’ll more quickly navigate the documentation to the exact information you need, which is actually a significant advantage given that there are really a lot of different ways to code a jQuery solution. It’s so robust that it’s easy to get hung up on implementation because of the number of solutions for a single problem. I’ve replicated here for you how the API is organized. I suggest memorizing the API outline, or at the very least the top-level categories.

  • jQuery Core

    • The jQuery Function

    • jQuery Object Accessors

    • Data

    • Plugins

    • Interoperability

  • Selectors

    • Basics

    • Hierarchy

    • Basic Filters

    • Content Filters

    • Visibility Filters

    • Attribute Filters

    • Child Filters

    • Forms

    • Form Filters

  • Attributes

    • Attr

    • Class

    • HTML

    • Text

    • Value

  • Traversing

    • Filtering

    • Finding

    • Chaining

  • Manipulation

    • Changing Contents

    • Inserting Inside

    • Inserting Outside

    • Inserting Around

    • Replacing

    • Removing

    • Copying

  • CSS

    • CSS

    • Positioning

    • Height and Widths

  • Events

    • Page Load

    • Event Handling

    • Live Events

    • Interaction Helpers

    • Event Helpers

  • Effects

    • Basics

    • Sliding

    • Fading

    • Custom

    • Settings

  • Ajax

    • AJAX Requests

    • AJAX Events

    • Misc.

  • Utilities

    • Browser and Feature Detection

    • Array and Object Operations

    • Test Operations

    • String Operations

    • Urls

Before we jump into a sequence of basic jQuery recipes, I would like to mention that the recipes found in this chapter build on each other. That is, there is a logical formation of knowledge as you progress from the first recipe to the last. It’s my suggestion, for your first reading of these recipes, that you read them in order from 1.1 to 1.17.

1.1. Including the jQuery Library Code in an HTML Page

Problem

You want to use the jQuery JavaScript library on a web page.

Solution

There are currently two ideal solutions for embedding the jQuery library in a web page:

  • Use the Google-hosted content delivery network (CDN) to include a version of jQuery (used in this chapter).

  • Download your own version of jQuery from jQuery.com and host it on your own server or local filesystem.

Discussion

Including the jQuery JavaScript library isn’t any different from including any other external JavaScript file. You simply use the HTML <script> element and provide the element a value (URL or directory path) for its src="" attribute, and the external file you are linking to will be included in the web page. For example, the following is a template that includes the jQuery library that you can use to start any jQuery project:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<script type="text/JavaScript">
    alert('jQuery ' + jQuery.fn.jquery);
</script>
</body>
</html>

Notice that I am using—and highly recommend using for public web pages—the Google-hosted minified version of jQuery. However, debugging JavaScript errors in minified code is not ideal. During code development, or on the production site, it actually might be better to use the nonminified version from Google for the purpose of debugging potential JavaScript errors. For more information about using the Google-hosted version of jQuery, you can visit the Ajax libraries API site on the Web at http://code.google.com/apis/ajaxlibs/.

It’s of course also possible, and mostly likely old hat, to host a copy of the jQuery code yourself. In most circumstances, however, this would be silly to do because Google has been kind enough to host it for you. By using a Google-hosted version of jQuery, you benefit from a stable, reliable, high-speed, and globally available copy of jQuery. As well, you reap the benefit of decreased latency, increased parallelism, and better caching. This of course could be accomplished without using Google’s solution, but it would most likely cost you a dime or two.

Now, for whatever reason, you might not want to use the Google-hosted version of jQuery. You might want a customized version of jQuery, or your usage might not require/have access to an Internet connection. Or, you simply might believe that Google is “The Man” and wish not to submit to usage because you are a control freak and conspiracy fanatic. So, for those who do not need, or simply who do not want, to use a Google-hosted copy of the jQuery code, jQuery can be downloaded from jQuery.com and hosted locally on your own server or local filesystem. Based on the template I’ve provided in this recipe, you would simply replace the src attribute value with a URL or directory path to the location of the jQuery JavaScript file you’ve downloaded.

1.2. Executing jQuery/JavaScript Coded After the DOM Has Loaded but Before Complete Page Load

Problem

Modern JavaScript applications using unobtrusive JavaScript methodologies typically execute JavaScript code only after the DOM has been completely loaded. And the reality of the situation is that any DOM traversing and manipulation will require that the DOM is loaded before it can be operated on. What’s needed is a way to determine when the client, most often a web browser, has completely loaded the DOM but has possibly not yet completely loaded all assets such as images and SWF files. If we were to use the window.onload event in this situation, the entire document including all assets would need to be completely loaded before the onload event fired. That’s just too time-consuming for most web surfers. What’s needed is an event that will tell us when the DOM alone is ready to be traversed and manipulated.

Solution

jQuery provides the ready() method, which is a custom event handler that is typically bound to the DOM’s document object. The ready() method is passed a single parameter, a function, that contains the JavaScript code that should be executed once the DOM is ready to be traversed and manipulated. The following is a simple example of this event opening an alert() window once the DOM is ready but before the page is completely loaded:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/JavaScript">
    jQuery(document).ready(function(){//DOM not loaded, must use ready event
        alert(jQuery('p').text());
    });
</script>
</head>
<body>
<p>The DOM is ready!</p>
</body>
</html>

Discussion

The ready() event handler method is jQuery’s replacement for using the JavaScript core window.onload event. It can be used as many times as you like. When using this custom event, it’s advisable that it be included in your web pages after the inclusion of stylesheet declarations and includes. Doing this will ensure that all element properties are correctly defined before any jQuery code or JavaScript code will be executed by the ready() event.

Additionally, the jQuery function itself provides a shortcut for using the jQuery custom ready event. Using this shortcut, the following alert() example can be rewritten like so:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
    jQuery(function(){ //DOM not loaded, must use ready event
        alert(jQuery('p').text());
    });
</script>
</head>
<body>
<p>The DOM is ready!</p>
</body>
</html>

The use of this custom jQuery event is necessary only if JavaScript has to be embedded in the document flow at the top of the page and encapsulated in the <head> element. I simply avoid the usage of the ready() event by placing all JavaScript includes and inline code before the closing <body> element. I do this for two reasons.

First, modern optimization techniques have declared that pages load faster when the JavaScript is loaded by the browser at the end of a page parse. In other words, if you put JavaScript code at the bottom of a web page, then the browser will load everything in front of it before it loads the JavaScript. This is a good thing because most browsers will typically stop processing other loading initiatives until the JavaScript engine has compiled the JavaScript contained in a web page. It’s sort of a bottleneck in a sense that you have JavaScript at the top of a web page document. I realize that for some situations it’s easier to place JavaScript in the <head> element. But honestly, I’ve never seen a situation where this is absolutely required. Any obstacle that I’ve encountered during my development by placing JavaScript at the bottom of the page has been easily overcome and well worth the optimization gains.

Second, if speedy web pages are our goal, why wrap more functionality around a situation that can be elevated by simply moving the code to the bottom of the page? When given the choice between more code or less code, I choose less code. Not using the ready() event results in using less code, especially since less code always runs faster than more code.

With some rationale out of the way, here is an example of our alert() code that does not use the ready() event:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>The DOM is ready!</p>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
     alert(jQuery('p').text());//go for it the DOM is loaded
</script>
</body>
</html>

Notice that I have placed all of my JavaScript before the closing </body> element. Any additional markup should be placed above the JavaScript in the HTML document.

1.3. Selecting DOM Elements Using Selectors and the jQuery Function

Problem

You need to select a single DOM element and/or a set of DOM elements in order to operate on the element(s) using jQuery methods.

Solution

jQuery provides two options when you need to select element(s) from the DOM. Both options require the use of the jQuery function (jQuery() or alias $()). The first option, which uses CSS selectors and custom selectors, is by far the most used and most eloquent solution. By passing the jQuery function a string containing a selector expression, the function will traverse the DOM and locate the DOM nodes defined by the expression. As an example, the following code will select all the <a> elements in the HTML document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/JavaScript">
     //alerts there are 6 elements
     alert('Page contains ' + jQuery('a').length +  ' <a> elements!');
</script>
</body>
</html>

If you were to run this HTML page in a web browser, you would see that the code executes a browser alert() that informs us that the page contains six <a> elements. I passed this value to the alert() method by first selecting all the <a> elements and then using the length property to return the number of elements in the jQuery wrapper set.

You should be aware that the first parameter of the jQuery function, as we are using it here, will also accept multiple expressions. To do this, simply separate multiple selectors with a comma inside the same string that is passed as the first parameter to the jQuery function. Here is an example of what that might look like:

jQuery('selector1, selector2, selector3').length;

Our second option for selecting DOM elements and the less common option is to pass the jQuery function an actual JavaScript reference to DOM element(s). As an example, the following code will select all the <a> elements in the HTML document. Notice that I’m passing the jQuery function an array of <a> elements collected using the getElementsByTagName DOM method. This example produces the same exact results as our previous code example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body bgcolor="yellow"> <!-- yes the attribute is depreciated, I know, roll 
with it -->
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/JavaScript">
     //alerts there are 6 elements
     alert('Page contains ' + jQuery(document.getElementsByTagName('a')).length +  
' <a> Elements, And has a '
     + jQuery(document.body).attr('bgcolor') + ' background');
</script>
</body>
</html>

Discussion

The heavy lifting that jQuery is known for is partially based on the selector engine, Sizzle, that selects DOM element(s) from an HTML document. While you have the option, and it’s a nice option when you need it, passing the jQuery function DOM references is not what put jQuery on everyone’s radar. It’s the vast and powerful options available with selectors that make jQuery so unique.

Throughout the rest of the book, you will find powerful and robust selectors. When you see one, make sure you fully understand its function. This knowledge will serve you well with future coding endeavors using jQuery.

1.4. Selecting DOM Elements Within a Specified Context

Problem

You need a reference to a single DOM element or a set of DOM elements in the context of another DOM element or document in order to operate on the element(s) using jQuery methods.

Solution

The jQuery function when passed a CSS expression will also accept a second parameter that tells the jQuery function to which context it should search for the DOM elements based on the expression. The second parameter in this case can be a DOM reference, jQuery wrapper, or document. In the following code, there are 12 <input> elements. Notice how I use a specific context, based on the <form> element, to select only particular <input> elements:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<form>
<input name="" type="checkbox" />
<input name="" type="radio" />
<input name="" type="text" />
<input name="" type="button" />
</form>

<form>
<input name="" type="checkbox" />
<input name="" type="radio" />
<input name="" type="text" />
<input name="" type="button" />
</form>

<input name="" type="checkbox" />
<input name="" type="radio" />
<input name="" type="text" />
<input name="" type="button" />

<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/JavaScript">

 //searches within all form elements, using a wrapper for context, alerts "8 inputs"
 alert('selected ' + jQuery('input',$('form')).length + ' inputs');

 //search with the first form element, using DOM reference as the context, alerts 
 //"4 inputs"
 alert('selected' + jQuery('input',document.forms[0]).length + ' inputs');

 //search within the body element for all input elements using an expression, 
 //alerts "12 inputs" 
 alert('selected' + jQuery('input','body').length + ' inputs');

</script>
</body>
</html>

Discussion

It’s also possible, as mentioned in the solution of this recipe, to select documents as the context for searching. For example, it’s possible to search within the context of an XML document that is sent back from doing an XHR request (Ajax). You can find more details about this usage in Chapter 16.

1.5. Filtering a Wrapper Set of DOM Elements

Problem

You have a set of selected DOM elements in a jQuery wrapper set but want to remove DOM elements from the set that do not match a new specified expression(s) in order to create a new set of elements to operate on.

Solution

The jQuery filter method, used on a jQuery wrapper set of DOM elements, can exclude elements that do not match a specified expression(s). In short, the filter() method allows you to filter the current set of elements. This is an important distinction from the jQuery find method, which will reduce a wrapped set of DOM elements by finding (via a new selector expression) new elements, including child elements of the current wrapped set.

To understand the filter method, let’s examine the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<a href="#" class="external">link</a>
<a href="#" class="external">link</a>
<a href="#"></a>
<a href="#" class="external">link</a>
<a href="#" class="external">link</a>
<a href="#"></a></li>
<a href="#">link</a>
<a href="#">link</a>
<a href="#">link</a>
<a href="#">link</a>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">

   //alerts 4 left in the set
       alert(jQuery('a').filter('.external').length + ' external links');
</script>
</body>
</html>

The HTML page in the code example just shown contains a web page with 10 <a> elements. Those links that are external links are given a class name of external. Using the jQuery function, we select all <a> elements on the page. Then, using the filter method, all those elements that do not have a class attribute value of external are removed from the original set. Once the initial set of DOM elements are altered using the filter() method, I invoke the length property, which will tell me how many elements are now in my new set after the filter has been applied.

Discussion

It’s also possible to send the filter() method a function that can be used to filter the wrapped set. Our previous code example, which passes the filter() method a string expression, can be changed to use a function instead:

alert(
   jQuery('a')
      .filter(function(index){ return $(this).hasClass('external');})
      .length + ' external links'
);

Notice that I am now passing the filter() method an anonymous function. This function is called with a context equal to the current element. That means when I use $(this) within the function, I am actually referring to each DOM element in the wrapper set. Within the function, I am checking each <a> element in the wrapper set to see whether the element has a class value (hasClass()) of external. If it does, Boolean true, then keep the element in the set, and if it doesn’t (false), then remove the element from the set. Another way to look at this is if the function returns false, then the element is removed. If the function returns any other data value besides false, then the element will remain in the wrapper set.

You may have noticed that I have passed the function a parameter named index that I am not using. This parameter, if needed, can be used to refer numerically to the index of the element in the jQuery wrapper set.

1.6. Finding Descendant Elements Within the Currently Selected Wrapper Set

Problem

You have a set of selected DOM elements (or a single element) and want to find descendant (children) elements within the context of the currently selected elements.

Solution

Use the .find() method to create a new wrapper set of elements based on the context of the current set and their descendants. For example, say that you have a web page that contains several paragraphs. Encapsulated inside of these paragraphs are words that are emphasized (italic). If you’d like to select only <em> elements contained within <p> elements, you could do so like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Ut ad videntur facilisis <em>elit</em> cum. Nibh insitam erat facit 
<em>saepius</em> magna.  Nam ex liber iriure et imperdiet. Et mirum eros 
iis te habent. </p>
<p>Claram claritatem eu amet dignissim magna. Dignissim quam elit facer eros 
illum. Et qui ex esse <em>tincidunt</em> anteposuerit. Nulla nam odio ii 
vulputate feugait.</p>
<p>In quis <em>laoreet</em> te legunt euismod. Claritatem <em>consuetudium</em> 
wisi sit velit facilisi.</p>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
 //alerts total italic words found inside of <p> elements
       alert('The three paragraphs in all contain ' + 
       jQuery('p').find('em').length + ' 
italic words');
</script>
</body>
</html>

Keep in mind that we could have also written this code by passing a contextual reference as a second parameter to the jQuery function:

alert('The three paragraphs in all contain ' + jQuery('em',$('p')).length + 
' italic words');

Additionally, it’s worth mentioning that the last two code examples are demonstrative in purpose. It is likely more logical, if not pragmatic, to use a CSS selector expression to select all the descendant italic elements contained within the ancestor <p> elements.

alert('The three paragraphs in all contain ' + jQuery('p em').length + 
' italic words');

Discussion

The jQuery .find() method can be used to create a new set of elements based on context of the current set of DOM elements and their children elements. People often confuse the use of the .filter() method and .find() method. The easiest way to remember the difference is to keep in mind that .find() will operate/select the children of the current set while .filter() will only operate on the current set of elements. In other words, if you want to change the current wrapper set by using it as a context to further select the children of the elements selected, use .find(). If you only want to filter the current wrapped set and get a new subset of the current DOM elements in the set only, use .filter(). To boil this down even more, find() returns children elements, while filter() only filters what is in the current wrapper set.

1.7. Returning to the Prior Selection Before a Destructive Change

Problem

A destructive jQuery method (e.g., filter() or find()) that was used on a set of elements needs to be removed so that the set prior to the use of the destructive method is returned to its previous state and can then be operated as if the destructive method had never been invoked.

Solution

jQuery provides the end() method so that you can return to the previous set of DOM elements that were selected before using a destructive method. To understand the end() method, let’s examine the following HTML.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>text</p>
<p class="middle">Middle <span>text</span></p>
<p>text</p>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
    alert(jQuery('p').filter('.middle').length); //alerts 1
    alert(jQuery('p').filter('.middle').end().length); //alerts 3
    alert(jQuery('p').filter('.middle').find('span')
.end().end().length); //alerts 3
</script>
</body>
</html>

The first alert() statement in the code contains a jQuery statement that will search the document for all <p> elements and then apply filter() to the selected <p> elements in the set selecting only the one(s) with a class of middle. The length property then reports how many elements are left in the set:

alert(jQuery('p').filter('.middle').length); //alerts 1

The next alert() statement makes use of the end() method. Here we are doing everything we did in the prior statement except that we are undoing the filter() method and returning to the set of elements contained in the wrapper set before the filter() method was applied:

alert(jQuery('p').filter('.middle').end().length); //alerts 3

The last alert() statement demonstrates how the end() method is used twice to remove both the filter() and find() destructive changes, returning the wrapper set to its original composition:

alert(jQuery('p').filter('.middle').find('span').end().end().length); //alerts 3

Discussion

If the end() method is used and there were no prior destructive operations performed, an empty set is returned. A destructive operation is any operation that changes the set of matched jQuery elements, which means any traversing or manipulation method that returns a jQuery object, including add(), andSelf(), children(), closes(), filter(), find(), map(), next(), nextAll(), not(), parent(), parents(), prev(), prevAll(), siblings(), slice(), clone(), appendTo(), prependTo(), insertBefore(), insertAfter(), and replaceAll().

1.8. Including the Previous Selection with the Current Selection

Problem

You have just manipulated a set of elements in order to acquire a new set of elements. However, you want to operate on the prior set as well as the current set.

Solution

You can combine a prior selection of DOM elements with the current selection by using the andSelf() method. For example, in the following code, we are first selecting all <div> elements on the page. Next we manipulate this set of elements by finding all <p> elements contained within the <div> elements. Now, in order to operate on both the <div> and the <p> elements found within the <div>, we could include the <div> into the current set by using andSelf(). Had I omitted the andSelf(), the border color would have only been applied to the <p> elements:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>
<p>Paragraph</p>
<p>Paragraph</p>
</div>
<script type="text/JavaScript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
    jQuery('div').find('p').andSelf().css('border','1px solid #993300');
</script>
</body>
</html>

Discussion

Keep in mind that when you use the andSelf() method, it will only add into the current set being operated on and the prior set, but not all prior sets.

1.9. Traversing the DOM Based on Your Current Context to Acquire a New Set of DOM Elements

Problem

You have selected a set of DOM elements, and based on the position of the selections within the DOM tree structure, you want to traverse the DOM to acquire a new set of elements to operate on.

Solution

jQuery provides a set of methods for traversing the DOM based on the context of the currently selected DOM element(s).

For example, let’s examine the following HTML snippet:

<div>
<ul>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
</ul>
</div>

Now, let’s select the second <li> element using the :eq() index custom selector:

//selects the second element in the set of <li>'s by index, index starts at 0
jQuery('li:eq(1)');

We now have a context, a starting point within the HTML structure. Our starting point is the second <li> element. From here we can go anywhere—well, almost anywhere. Let’s see where we can go using a couple of the methods jQuery provides for traversing the DOM. Read the comments in the code for clarification:

jQuery('li:eq(1)').next() //selects the third <li>

jQuery('li:eq(1)').prev() //selects the first <li>

jQuery('li:eq(1)').parent() //selects the <ul>

jQuery('li:eq(1)').parent().children() //selects all <li>s

jQuery('li:eq(1)').nextAll() //selects all the <li>s after the second <li>

jQuery('li:eq(1)').prevAll() //selects all the <li>s before the second <li>

Keep in mind that these traversing methods produce a new wrapper set, and to return to the previous wrapper set, you can use end().

Discussion

The traversing methods shown thus far have demonstrated simple traverses. There are two additional concepts that are important to know about traversing.

The first concept and likely most obvious is that traversing methods can be chained. Let’s examine again the following jQuery statement from earlier:

jQuery('li:eq(1)').parent().children() //selects all <li>'s

Notice that I have traversed from the second <li> element to the parent <ul> element and then again traversed from the parent element to selecting all the children elements of the <ul> element. The jQuery wrapper set will now contain all the <li> elements contained within the <ul>. Of course, this is a contrived example for the purpose of demonstrating traversing methods. Had we really wanted a wrapper set of just <li> elements, it would have been much simpler to select all the <li> elements from the get-go (e.g., jQuery('li')).

The second concept that you need to keep in mind when dealing with the traversing methods is that many of the methods will accept an optional parameter that can be used to filter the selections. Let’s take our chained example again and look at how we could change it so that only the last <li> element was selected. Keep in mind that this is a contrived example for the purpose of demonstrating how a traversing method can be passed an expression used for selecting a very specific element:

jQuery('li:eq(1)').parent().children(':last') //selects the last <li>

jQuery provides additional traversing methods that were not shown here. For a complete list and documentation, have a look at http://docs.jquery.com/Traversing. You will find these additional traversing methods used throughout this book.

1.10. Creating, Operating on, and Inserting DOM Elements

Problem

You want to create new DOM elements (or a single element) that are immediately selected, operated on, and then injected into the DOM.

Solution

If you haven’t figured it out yet, the jQuery function is multifaceted in that this one function performs differently depending upon the makeup of the parameter(s) you send it. If you provide the function with a text string of raw HTML, it will create these elements for you on the fly. For example, the following statement will create an <a> element wrapped inside of a <p> element with a text node encapsulated inside of the <p> and <a> elements:

jQuery('<p><a>jQuery</a></p>');

Now, with an element created, you can use jQuery methods to further operate on the elements you just created. It’s as if you had selected the <p> element from the get-go in an existing HTML document. For example, we could operate on the <a> by using the .find() method to select the <a> element and then set one of its attributes. In the case of the following code, we are setting the href attribute with a value of http://www.jquery.com:

jQuery('<p><a>jQuery</a></p>').find('a').attr('href','http://www.jquery.com');

This is great, right? Well, it’s about to get better because all we have done so far is create elements on the fly and manipulate those elements in code. We have yet to actually change the currently loaded DOM, so to speak. To do this, we’ll have to use the manipulation methods provided by jQuery. The following is our code in the context of an HTML document. Here we are creating elements, operating on those elements, and then inserting those elements into the DOM using the appendTo() manipulation method:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
jQuery('<p><a>jQuery</a></p>').find('a').attr('href','http://www.jquery.com')
  .end().appendTo('body');
</script>
</body>
</html>

Notice how I am using the end() method here to undo the find() method so that when I call the appendTo() method, it appends what was originally contained in the initial wrapper set.

Discussion

In this recipe we’ve passed the jQuery function a string of raw HTML that is taken and used to create DOM elements on the fly. It’s also possible to simply pass the jQuery function a DOM object created by the DOM method createElement():

jQuery(document.createElement('p')).appendTo('body'); //adds an empty p element 
to the page

Of course, this could be rather laborious depending upon the specifics of the usage when a string of HTML containing multiple elements will work just fine.

It’s also worth mentioning here that we’ve only scratched the surface of the manipulation methods by using the appendTo() method. In addition to the appendTo() method, there are also the following manipulation methods:

  • append()

  • prepend()

  • prependTo()

  • after()

  • before()

  • insertAfter()

  • insertBefore()

  • wrap()

  • wrapAll()

  • wrapInner()

1.11. Removing DOM Elements

Problem

You want to remove elements from the DOM.

Solution

The remove() method can be used to remove a selected set of elements and their children elements from the DOM. Examine the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h3>Anchors</h3>
<a href='#'>Anchor Element</a>
<a href='#'>Anchor Element</a>
<a href='#'>Anchor Element</a>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
  jQuery('a').remove();
</script>
</body>
</html>

When the preceding code is loaded into a browser, the anchor elements will remain in the page until the JavaScript is executed. Once the remove() method is used to remove all anchor elements from the DOM, the page will visually contain only an <h3> element.

It’s also possible to pass the method an expression to filter the set of elements to be removed. For example, our code could change to remove only anchors with a specific class:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h3>Anchors</h3>
<a href='#' class='remove'>Anchor Element</a>
<a href='#'>Anchor Element</a>
<a href='#' class="remove">Anchor Element</a>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
  jQuery('a').remove('.remove');
</script>
</body>
</html>

Discussion

When using the jQuery remove() method, you need to keep two things in mind:

  • While the elements selected are removed from the DOM using remove(), they have not been removed from the jQuery wrapper set. That means in theory you could continue operating on them and even add them back into the DOM if desired.

  • This method will not only remove the elements from the DOM, but it will also remove all event handlers and internally cached data that the elements removed might have contained.

1.12. Replacing DOM Elements

Problem

You need to replace DOM nodes currently in the DOM with new DOM nodes.

Solution

Using the replaceWith() method, we can select a set of DOM elements for replacement. In the following code example, we use the replaceWith() method to replace all <li> elements with a class attribute of remove with a new DOM structure:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<ul>
<li class='remove'>name</li>
<li>name</li>
<li class='remove'>name</li>
<li class='remove'>name</li>
<li>name</li>
<li class='remove'>name</li>
<li>name</li>
<li class='remove'>name</li>
</ul>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
  jQuery('li.remove').replaceWith('<li>removed</li>');
</script>
</body>
</html>

The new DOM structure added to the DOM is a string parameter passed into the replaceWith() method. In our example, all the <li> elements, including children elements, are replaced with the new structure, <li>removed</li>.

Discussion

jQuery provides an inverse to this method called replaceAll() that does the same task with the parameters reversed. For example, we could rewrite the jQuery code found in our recipe code like so:

jQuery('<li>removed</li>').replaceAll('li.remove');

Here we are passing the jQuery function the HTML string and then using the replaceAll() method to select the DOM node and its children that we want to be removed and replaced.

1.13. Cloning DOM Elements

Problem

You need to clone/copy a portion of the DOM.

Solution

jQuery provides the clone() method for copying DOM elements. Its usage is straightforward. Simply select the DOM elements using the jQuery function, and then call the clone() method on the selected set of element(s). The result is a copy of the DOM structure being returned for chaining instead of the originally selected DOM elements. In the following code, I am cloning the <ul> element and then appending this copy back into the DOM using the inserting method appendTo(). Essentially, I am adding another <ul> structure to the page exactly like the one that is already there:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<ul>
<li>list</li>
<li>list</li>
<li>list</li>
<li>list</li>
</ul>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
 jQuery('ul').clone().appendTo('body');
</script>
</body>
</html>

Discussion

The cloning method is actually very handy for moving DOM snippets around inside of the DOM. It’s especially useful when you want to not only copy and move the DOM elements but also the events attached to the cloned DOM elements. Closely examine the HTML and jQuery here:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<ul id="a">
<li>list</li>
<li>list</li>
<li>list</li>
<li>list</li>
</ul>
<ul id="b"></ul>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
 jQuery('ul#a li')
    .click(function(){alert('List Item Clicked')})
    .parent()
        .clone(true)
            .find('li')
            .appendTo('#b')
        .end()
    .end()
    .remove();
</script>
</body>
</html>

If you were to run this code in a browser, it would clone the <li> elements on the page that have a click event attached to them, insert these newly cloned elements (including events) into the empty <ul>, and then remove the <ul> element that we cloned.

This might stretch a new jQuery developer’s mind, so let’s examine this jQuery statement by stepping through this code in order to explain the chained methods:

  1. jQuery('ul#a li') = Select <ul> element with an id attribute of a and then select all the <li> elements inside of the <ul>.

  2. .click(function(){alert('List Item Clicked')}) = Add a click event to each <li>.

  3. .parent() = Traverse the DOM, by changing my selected set to the <ul> element.

  4. .clone(true) = Clone the <ul> element and all its children, including any events attached to the elements that are being cloned. This is done by passing the clone() method a Boolean value of true.

  5. .find('li') = Now, within the cloned elements, change the set of elements to only the <li> elements contained within the cloned <ul> element.

  6. .appendTo('#b') = Take these selected cloned <li> elements and place them inside of the <ul> element that has an id attribute value of b.

  7. .end() = Return to the previous selected set of elements, which was the cloned <ul> element.

  8. .end() = Return to the previous selected set of elements, which was the original <ul> element we cloned.

  9. .remove() = Remove the original <ul> element.

If it’s not obvious, understanding how to manipulate the selected set of elements or revert to the previous selected set is crucial for complex jQuery statements.

1.14. Getting, Setting, and Removing DOM Element Attributes

Problem

You have selected a DOM element using the jQuery function and need to get or set the value of the DOM element’s attribute.

Solution

jQuery provides the attr() method for getting and setting attribute values. In the following code, we are going to be setting and then getting the value of an <a> element’s href attribute:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<a>jquery.com</a>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/JavaScript">
// alerts the jQuery home page URL
alert(
    jQuery('a').attr('href','http://www.jquery.com').attr('href')
);
</script>
</body>
</html>

As you can see in the code example, we are selecting the only <a> element in the HTML document, setting its href attribute, and then getting its value with the same attr() method by passing the method the attribute name alone. Had there been multiple <a> elements in the document, the attr() method would access the first matched element. The code when loaded into a browser will alert() the value that we set for the href attribute.

Now, since most elements have more than one attribute available, it’s also possible to set multiple attribute values using a single attr() method. For example, we could also set the title attribute in the previous example by passing the attr() method an object instead of two string parameters:

jQuery('a').attr({'href':'http://www.jquery.com','title':'jquery.com'}).attr('href')

With the ability to add attributes to elements also comes the ability to remove attributes and their values. The removeAttr() method can be used to remove attributes from HTML elements. To use this method, simply pass it a string value of the attribute you’d like to remove (e.g., jQuery('a')removeAttr('title')).

Discussion

In addition to the attr() method, jQuery provides a very specific set of methods for working with the HTML element class attribute. Since the class attribute can contain several values (e.g., class="class1 class2 class3"), these unique attribute methods are used to manage these values.

These jQuery methods are as follows:

addClass()

Updates the class attribute value with a new class/value including any classes that were already set

hasClass()

Checks the value of the class attribute for a specific class

removeClass()

Removes a unique class from the class attribute while keeping any values already set

toggleClass()

Adds the specified class if it is not present; removes the specified class if it is present

1.15. Getting and Setting HTML Content

Problem

You need to get or set a chunk of HTML content in the current web page.

Solution

jQuery provides the html() method for getting and setting chunks (or DOM structures) of HTML elements. In the following code, we use this method to set and then get the HTML value of the <p> element found in the HTML document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p></p>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/JavaScript">
jQuery('p').html('<strong>Hello World</strong>, I am a <em>&lt;p&gt;</em> element.');
alert(jQuery('p').html());
</script>
</body>
</html>

Running this code in a browser will result in a browser alerting the HTML content contained within the <p> element, which we set using the html() method and then retrieved using the html() method.

Discussion

This method uses the DOM innerHTML property to get and set chunks of HTML. You should also be aware that html() is not available on XML documents (although it will work for XHTML documents).

1.16. Getting and Setting Text Content

Problem

You need to get or set the text that is contained inside of an HTML element(s).

Solution

jQuery provides the text() method for getting and setting the text content of elements. In the following code, we use this method to set and then get the text value of the <p> element found in the HTML document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p></p>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/JavaScript">
     jQuery('p').text('Hello World, I am a <p> element.');
     alert(jQuery('p').text());
</script>
</body>
</html>

Running this code in a browser will result in a browser alerting the content of the <p> element, which we set using the text() method and then retrieved using the text() method.

Discussion

It’s important to remember that the text() method is not unlike html() except that the text() method will escape HTML (replace < and > with their HTML entities). This means that if you place tags inside of the text string passed to the text() method, it will convert these tags to their HTML entities (&lt; and &gt;).

1.17. Using the $ Alias Without Creating Global Conflicts

Problem

You want to use the shortcut $ alias instead of typing the global namespace name (jQuery) without fear of global conflicts.

Solution

The solution here is to create an anonymous self-invoking function that we pass the jQuery object to and then use the $ character as a parameter pointer to the jQuery object.

For example, all jQuery code could be encapsulated inside the following self-invoking function:

(function($){ //function to create private scope with $ parameter
    //private scope and using $ without worry of conflict
})(jQuery); //invoke nameless function and pass it the jQuery object

Discussion

Essentially, what is going on here is that we have passed the global reference to jQuery to a function that creates a private scope. Had we not done this and chosen to use the shorthand $ alias in the global scope, we would be taking a risk by assuming that no other scripts included in the HTML document (or scripts included in the future) use the $ character. Why risk it when you can just create your own private scope?

Another advantage to doing this is that code included inside of the anonymous self-invoking function will run in its own private scope. You can rest assured that anything that is placed inside the function will likely never cause a conflict with other JavaScript code written in the global scope. So, again, why risk programmatic collisions? Just create your own private scope.

Get jQuery Cookbook 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.