Published: 29 Oct 2008
By: Karl Seguin

JQuery is a lightweight, yet powerful, JavaScript library specializing in DOM traversal and manipulation, event handling, and extensibility. It is quickly becoming the premiere JavaScript library of choice due to its elegant and simple syntax.

Contents [hide]

Introduction

The last couple years has seen developers assaulted with an ever-increasing number of JavaScript libraries and frameworks. Few have received the same universal and long-lasting praise as JQuery. I attribute the success of this particular framework to two aspects. First, JQuery is extremely focused in its design. Instead of giving you the world, the core JQuery framework largely revolves around:

  1. Traversing the DOM (finding elements on the page well beyond the capability of document.getElementById),
  2. Manipulating the DOM (changing the properties and behaviors of the elements on the page), and
  3. Making it easy to develop plug-ins.

Secondly, JQuery’s syntax is extremely intuitive and light – making it quick to learn and quick to remember. In this article we’ll look at each of these aspects to provide the foundation necessary to leverage this great tool.

DOM Traversal

Simply getting elements might seem mundane at first, but JQuery’s capabilities are so complete and simple to use, you’ll quickly see this as the core of all your JavaScript needs. Like many other frameworks, JQuery heavily relies on the $ function (known as the JQuery function). You should think of the $ function as meaning “find these elements” (it can be used for more, such as “create these elements”, but we’ll simply focus on traversal). It expects a single string parameter which is the selector for the item you are looking for. Two simple examples are:

When the selector starts with a # JQuery looks for an element with the matching id (id= "help"), and as such behaves like document.getElementById. The second example selects all of the <p> tags. If you’re familiar with CSS, you might have noticed that both these examples work exactly like CSS selectors. This is intentional – in fact, if you’re remotely good with CSS then learning JQuery will be much easier. It’s worth mentioning that JQuery is cross-browser compatible. So even if IE 6 doesn’t support the CSS attribute selector, it will work in JQuery. What’s the attribute selector? It lets you find an element based on the value of one of its attributes. For example, say we wanted the UserName input box, we could use:

There are two very important things to know about the JQuery function. First, it always returns an array. Even if you know only a single item will be returned (such as when you use the id selector), you’ll always get an array. When no items are found, it’ll return an array of zero elements. Secondly, it always returns a JQuery object. From now on, as a matter of convention (you don’t have to do this if you don’t want), we’ll always assign the result to a variable prefixed with the dollar sign. So our previous example becomes:

The JQuery object has a number of methods that allow us to manipulate the underlying element as well as set-up events. The fact that we’re dealing with an array makes it painless to do this on sets of elements. If necessary, we can always get the actual DOM element via the get method:

We can use the length property to find out how many elements were found:

The above example is again using basic CSS selectors – all elements with a class of row which are children of the id=”list” element.

Since you can find a detailed list of all supported selectors on the JQuery website, we won’t dwell much longer on this topic. Do know however that you can do some advanced things, like:

This actually highlights another nice feature of the JQuery object – it supports method chaining (also known as Fluent Interfaces). We’ll see more of this when you look at manipulation next.

Let’s look at two final points on traversal. First, the JQuery function accepts a second parameter which is the context from where it ought to search. By default, it’ll search the entire DOM. However, we can search only a subset of the document:

Second, you can use the JQuery function to turn a normal DOM element into a JQuery object:

DOM Manipulation

Now that we know how to get JQuery objects, it time we started doing something useful with them – besides assigning them to variables. A common scenario is applying a specific CSS to the alternating rows of a table.

Keep in mind that you don’t need to actually declare an “.alt” style – this can simply be a marker for JQuery. Also remember that you can apply multiple classes to an element. For example, we can apply a “main” style to our table while also applying our “alt” marker by separating the two with a space:

We can also get or set the content of an element:

The above code would work with the following HTML:

Of course, beyond the simple object manipulation, JQuery also provides helpful methods to move/append/insert/remove elements, as well as some basic effects:

You can find many more in the official JQuery documentation.

Events

The last aspect of JQuery that we’ll look at, in this part, are events. We now know how to select and manipulate elements, but toggling help isn’t really useful unless it’s in response to some user-initiated event. The most important one that you’ll use is JQuery’s own ready event. This tells you that the DOM is ready to be traversed and manipulated. You use this method instead of the typical onload event – it not only handles multiple handlers properly, but also fires before onload, which should provide better performance and cleaner UI rendering:

The above code can be a little intimidating to new programmers. For now, you can just copy-and-paste it as needed. However, if you actually look at it, you’ll realize how simple it is:

  • First, it turns the document element into a JQuery object
  • Next, it executes the ready function which itself expects a function
  • Finally, you provide the body of the function supplied to ready

All of the code that we’ve looked at so far (except the HTML fragment obviously) needs to be placed inside the above code (you can have multiple ready events per page).

We can now build our own event handlers:

The above code is applying a hover event to all rows within our partList. Hover, expects two arguments. The first is the function to execute when entering the hover state; the second is the function to execute when leaving the hover state. You might be wondering what’s up with $(this). In JavaScript the element on which an event occurs on is always available as this within the event handler. $(this) is simply the JQuery function applied to that element (much like $(document)).

We can further extend our partList by adding a click event:

Which would work with the following HTML:

There are many other events, beyond hover and click that you can bind to – such as form submit, input changed, key press, double click and so on. A complete list is available at the here.

Summary

This article was meant to provide a quick introduction to the core functionality of JQuery, namely DOM traversal and manipulation. There are a couple key points worth repeating:

  • JQuery code should be placed within the $(document).ready(function() {…}); block
  • The JQuery method ($) returns JQuery objects,
  • The JQuery method ($) always returns an array
  • Following sections will look at more complex usage of JQuery, as well as how to build our own plug-ins and JQuery unit testing.
<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Karl Seguin

Karl Seguin is an senior application developer at Fuel Industries, located in Ottawa, Ontario. He's an editor here at DotNetSlackers, a blogger for the influential CodeBetter.com and a Microsoft MVP.

This author has published 8 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Animating a Web Form using ASP.NET AJAX
In this article you will learn how to animate a webform using asp.net ajax.
Jquery Ajax
JQuery makes communicating with the server very, very easy. JQuery uses get(), getJSON(), and post(...
jQuery Deferred Objects Promise Callbacks
jQuery Deferred/Promise objects untangle spaghetti-like asynchronous code.
jQuery in Action 2nd edition: Queuing functions for execution
This article is taken from the book jQuery in Action, second edition. This segment shows how you can...
Test120Jan
This is my custom article

You might also be interested in the following related blog posts


CRUD Operations using Partial View and jQueryUI in ASP.NET MVC4 - Part 2 read more
Introducing SharePoint 2010 Training at U2U read more
The Underground at PDC read more
Assembly-Free jQuery in SharePoint Sites Using the SmartTools jQueryLoader read more
My History of Visual Studio (Part 6) read more
BeginDialOut with Office Communicator Clients read more
DotNetNuke Fusion Results for Q3 read more
GiveCamps Get a new Sponsor read more
Announcing the WebsiteSpark Program read more
Scenarios for WS-Passive and OpenID read more
Top
 
 
 

Discussion


Subject Author Date
placeholder onload, not unload Vladimir Kelman 11/8/2008 1:01 AM
RE: onload, not unload Karl Seguin 11/8/2008 11:15 AM
placeholder RE: RE: onload, not unload Sonu Kapoor 11/8/2008 11:40 AM
Chaining method calls? Vladimir Kelman 11/12/2008 4:06 PM
placeholder RE: Chaining method calls? Karl Seguin 11/12/2008 5:59 PM
Functional pleasure Vladimir Kelman 11/12/2008 6:59 PM

Please login to rate or to leave a comment.