O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 1. jQuery Basics

Cody Lindley


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"
<script type="text/JavaScript" 
<div>old content</div>

//hide all divs on the page

//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

//show all divs on the page


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()).


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

//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

//show all divs on the page

to this:

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

or, with indenting and line breaks, to this:

    .text('new content')

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"
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/
jquery/1.3.0/jquery.min.js"></script> </head>
<div>old content</div>
<div>old content</div>
<div>old content</div>
<div>old content</div>
//hide all divs on the page
jQuery('div').hide().text('new content').addClass("updatedContent").show();


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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required