Tutorials:Getting Started with jQuery

Setup

To start, we need a copy of the jQuery library, which we can get from the main download page. The jQuery Starterkit provides some markup and CSS to work with. After downloading and extracting its content we put jquery.js into the same directory and open starterkit.html and custom.js with our favorite editor and starterkit.html with a browser.

Now we have everything to start with the notorious "Hello world" example.

Hello jQuery

We start with an empty html page:

<html>

<head>

<script type="text/javascript" src="jquery.js"</script>

<script type="text/javascript">

// we will add our javascript code here

</script>

</head>

<body>

<!-- we will add our HTML content here -->

</body>

</html>

This page just loads the jquery.js library (make sure the URL points to where you stored your copy of jquery! This example assumes that you store it in the same directory as this example file). Two comments indicate where we will expand this template with code.

As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.

To do this, we register a ready event for the document.

$(document).ready(function() {

// do stuff when DOM is ready

});

Putting an alert into that function does not make much sense, as an alert does not require the DOM to be loaded. So lets try something a little more sophisticated: Show an alert when clicking a link.

Add the following to the <body>:

<a href="">Link</a>

Now update the $(document).ready handler:

$(document).ready(function() {

$("a").click(function() {

alert("Hello world!");

});

});

This should show the alert as soon as you click on the link.

Lets have a look at what we are doing: $("a") is a jQuery selector, in this case, it selects all a elements. $ itself is an alias for the jQuery "class", therefore $() constructs a new jQuery object. The click() function we call next is a method of the jQuery object. It binds a click event to all selected elements (in this case, a single anchor element) and executes the provided function when the event occurs.

This is similar to the following code:

<a href="" onclick="alert('Hello world')">Link</a>

The difference is quite obvious: We don't need to write an onclick for every single element. We have a clean separation of structure (HTML) and behavior (JS), just as we separate structure and presentation by using CSS.

With this in mind, we explore selectors and events a little further.

Interesting links for this section:

  • jQuery Base
  • jQuery Expressions
  • jQuery Basic Events

Find me: Using selectors and events

jQuery provides two approaches to select elements. The first uses a combination of CSS and XPath selectors passed as a string to the jQuery constructor (eg. $("div > ul a")). The second uses several methods of the jQuery object. Both approaches can be combined.

To try some of these selectors, we select and modify the first ordered list in our starterkit.

To get started, we want to select the list itself. The list has an ID "orderedlist". In classic JavaScript, you could select it by using document.getElementById("orderedlist"). With jQuery, we do it like this:

$(document).ready(function() {

$("#orderedlist").addClass("red");

});

The starterkit provides a stylesheet with a class "red" that simply adds a red background. Therefore, when you reload the page in your browser, you should see that the first ordered list has a red background. The second list is not modified.

Now lets add some more classes to the child elements of this list.

$(document).ready(function() {

$("#orderedlist > li").addClass("blue");

});

This selects all child lis of the element with the id orderedlist and adds the class "blue".

Now for something a little more sophisticated: We want to add and remove the class when the user hovers the li element, but only on the last element in the list.

$(document).ready(function() {

$("#orderedlist li:last").hover(function() {

$(this).addClass("green");

},function(){

$(this).removeClass("green");

});

});

There are many other selectors similar to CSS and XPath syntax. More examples and a list of all available expressions can be found here.

For every onxxx event available, like onclick, onchange, onsubmit, there is a jQuery equivalent. Some other events, like ready and hover, are provided as convenient methods for certain tasks.

You can find a complete list of all events in the jQuery Events Documentation.

With those selectors and events you can already do a lot of things, but there is more.

$(document).ready(function() {

$("#orderedlist").find("li").each(function(i) {

$(this).append( " BAM! " + i );

});

});

find() allows you to further search the descendants of the already selected elements, therefore $("#orderedlist").find("li") is mostly the same as $("#orderedlist li").

each() iterates over every element and allows further processing. Most methods, like addClass(), use each() themselves.

In this example, append() is used to append some text to it and set it as text to the end of each element.

Another task you often face is to call methods on DOM elements that are not covered by jQuery. Think of a form you would like to reset after you submitted it successfully via AJAX.

$(document).ready(function() {

// use this to reset a single form

$("#reset").click(function() {

$("form")[0].reset();

});

});

This code selects the first form element and calls reset() on it. In case you had more than one form, you could also do this:

$(document).ready(function() {

// use this to reset several forms at once

$("#reset").click(function() {

$("form").each(function() {

this.reset();

});

});

});

This would select all forms within your document, iterate over them and call reset() for each. Note that in an .each() function, this refers to the actual element. Also note that, since the reset() function belongs to the form element and not to the jQuery object, we cannot simply call $("form").reset() to reset all the forms on the page.

An additional challenge is to select only certain elements from a group of similar or identical ones. jQuery provides filter() and not() for this. While filter() reduces the selection to the elements that fit the filter expression, not() does the contrary and removes all elements that fit the expression. Think of an unordered list where you want to select all li elements that have no ul children.

$(document).ready(function() {

$("li").not(":has(ul)").css("border", "1px solid black");

});

This selects all li elements that have a ul element as a child and removes all elements from the selection. Therefore all li elements get a border, except the one that has a child ul.

The [expression] syntax is taken from XPath and can be used to filter by attributes. Maybe you want to select all anchors that have a name attribute:

$(document).ready(function() {

$("a[name]").css("background", "#eee" );

});

This adds a background color to all anchor elements with a name attribute.

More often than selecting anchors by name, you might need to select anchors by their "href" attribute. This can be a problem as browsers behave quite inconsistently when returning what they think the "href" value is (Note: This problem was fixed recently in jQuery, available in any versions after 1.1.1). To match only a part of the value, we can use the contains select "*=" instead of an equals ("="):

$(document).ready(function() {

$("a[href*=/content/gallery]").click(function() {

// do something with all links that point somewhere to /content/gallery

});

});

Until now, all selectors were used to select children or filter the current selection. There are situations where you need to select the previous or next elements, known as siblings. Think of a FAQ page, where all answers are hidden first, and shown, when the question is clicked. The jQuery code for this:

$(document).ready(function() {

$('#faq').find('dd').hide().end().find('dt').click(function() {

$(this).next().slideToggle();

});

});

Here we use some chaining to reduce the code size and gain better performance, as '#faq' is only selected once. By using end(), the first find() is undone, so we can start search with the next find() at our #faq element, instead of the dd children.

Within the click handler, the function passed to the click() method, we use $(this).next() to find the next sibling starting from the current dt. This allows us to quickly select the answer following the clicked question.

In addition to siblings, you can also select parent elements (also known as ancestors for those more familiar with XPath). Maybe you want to highlight the paragraph that is the parent of the link the user hovers. Try this:

$(document).ready(function(){

$("a").hover(function(){

$(this).parents("p").addClass("highlight");

},function(){

$(this).parents("p").removeClass("highlight");

});

});

For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed.

Lets go one step back before continuing: jQuery is a lot about making code shorter and therefore easier to read and maintain. The following is a shortcut for the $(document).ready(callback) notation:

$(function() {

// code to execute when the DOM is ready

});

Applied to the Hello world! example, we end with this:

$(function() {

$("a").click(function() {

alert("Hello world!");

});

});

Now, with the basics at hand, we want to explore some other aspects, starting with AJAX.

Interesting links for this chapter:

  • jQuery API documentation
  • Visual jQuery - A categorized browsable API documentation.
  • jQuery Selectors
  • jQuery Events
  • jQuery DOM Traversing

API/1.1.2/DOM/Traversing/Selectors

jQuery selectors are a combination of CSS 1-3, XPath, plus some custom code to glue it together. Essentially, the best parts from both of these query languages were taken, combined, and used to create the final jQuery expression language. If you already know CSS (which most web developers do) then you're going to be fine.

If you are unsure about the general differences between the techniques discussed here, these articles in the English Wikipedia may help clarify a lot: XPath and [

Using CSS and XPath Together

This is a point of confusion, for some: How can you use CSS and XPath together, they're so different! jQuery makes some allowances to make this happen, but we think that developers will really appreciate the advantages of each language. Here are some examples:

Hide all Paragraph elements that contain a class attribute:

$("p[@class]").hide();

Show the first paragraph on the page:

$("p:eq(0)").show();

Hide all divs that are currently showing:

$("div:visible").hide();

Get all list items that are children of an unordered list:

$("ul/li")

/* valid too: $("ul > li") */

Get all Paragraphs, with a class of 'foo', that have a link in them:

$("p.foo[a]");

Get list item that contains link with "Register" text inside:

$("li[a:contains('Register')]");

Get the input field's value with the name of 'bar':

$("input[@name=bar]").val();

All checked radio buttons:

$("input[@type=radio][@checked]")

If you still have questions concerning how this selector language works, please feel free to post to the mailing list.

CSS Selectors

jQuery has full CSS 1-2 support and partial CSS 3 support, along with some custom CSS-like functionality (and XPath), as part of its expression.

For info on how CSS works feel free to read the various links:

  • CSS 1
  • CSS 2
  • CSS 3

What follows is a list of supported CSS Selector expressions.

  • * any element
  • E an element of type E
  • E:nth-child(n) an E element, the n-th child of its parent
  • E:first-child an E element, first child of its parent
  • E:last-child an E element, last child of its parent
  • E:only-child an E element, only child of its parent
  • E:empty an E element that has no children (including text nodes)
  • E:enabled a user interface element E which is not disabled
  • E:disabled a user interface element E which is disabled
  • E:checked a user interface element E which is checked (for instance a radio-button or checkbox)
  • E:selected a user interface element E which is selected (one or more option elements inside a select) - not in the CSS spec, but nonetheless supported by jQuery
  • E.warning an E element whose class is "warning"
  • E#myid an E element with ID equal to "myid". (Will only match, at most, one element.)
  • E:not(s) an E element that does not match simple selector s
  • E F an F element descendant of an E element
  • E > F an F element child of an E element
  • E + F an F element immediately preceded by an E element
  • E ~ F an F element preceded by an E element
  • E,F,G select all E elements, F elements, and G elements

Supported, but different

All attribute selectors are written like their XPath counter-parts (in that all attributes should begin with an @ symbol).

  • E[@foo] an E element with a "foo" attribute
  • E[@foo=bar] an E element whose "foo" attribute value is exactly equal to "bar"
  • E[@foo^=bar] an E element whose "foo" attribute value begins exactly with the string "bar"
  • E[@foo$=bar] an E element whose "foo" attribute value ends exactly with the string "bar"
  • E[@foo*=bar] an E element whose "foo" attribute value contains the substring "bar"
  • E[@foo=bar][@baz=bop] an E element whose "foo" attribute value is exactly equal to "bar" and whose "baz" attribute is exactly equal to "bop"

Not supported

jQuery only supports selectors that actually select DOM elements - everything else is ignored.

  • E:link
  • E:visited an E element being the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited)
  • E:active
  • E:hover
  • E:focus an E element during certain user actions
  • E:target an E element being the target of the referring URI
  • E::first-line the first formatted line of an E element
  • E::first-letter the first formatted letter of an E element
  • E::selection the portion of an E element that is currently selected/highlighted by the user
  • E::before generated content before an E element
  • E::after generated content after an E element

jQuery doesn't support the following selectors due to their lack of real-world usefulness:

  • E:nth-last-child(n) an E element, the n-th child of its parent, counting from the last one
  • E:nth-of-type(n) an E element, the n-th sibling of its type
  • E:nth-last-of-type(n) an E element, the n-th sibling of its type, counting from the last one
  • E:first-of-type an E element, first sibling of its type
  • E:last-of-type an E element, last sibling of its type
  • E:only-of-type an E element, only sibling of its type
  • E:lang(fr) an element of type E in language "fr"
  • E[foo~="test"] an E element whose "foo" attribute value is a list of space-separated values, one of which is exactly equal to "test"
  • E[hreflang|="en"] an E element whose "hreflang" attribute has a hyphen-separated list of values beginning (from the left) with "en"

Context and Anchoring

In jQuery, unlike real CSS, a selector expression may have a context other than the entire document, for instance with the function $(expr, context). You can anchor a CSS-like expression to the context root by starting it with one of the selectors , +, or ~.

XPath Selectors

One of the selector languages that jQuery supports, as a part of its expression language is XPath. jQuery supports basic XPath expressions, in addition to CSS 1-3. Here are some samples:

Location Paths

  • Relative to the entire HTML document

$("/html/body//p")

$("body//p")

$("p/../div")

  • Relative to the context node this

$("p/*", this)

$("/p//a", this)

Supported Axis Selectors

  • Descendant Element has a descendant element

$("//div//p")

  • Child Element has a child element

$("//div/p")

  • Preceding Sibling Element has an element before it, on the same axes

$("//div ~ form")

  • Parent Selects the parent element of the element

$("//div/../p")

Supported Predicates

  • [@foo] Has an attribute of foo

$("//input[@checked]")

  • [@foo='test'] Attribute foo is equal to test

$("//a[@ref='nofollow']")

  • [Nodelist] Element contains a node list, for example:

$("//div[p]")

$("//div[p/a]")

Supported Predicates, but differently

  • [last()] or [position()=last()] becomes :last

$("p:last")

  • [0] or [position()=0] becomes :eq(0) or:first

$("p:first")

$("p:eq(0)")

  • [position() < 5] becomes :lt(5)

$("p:lt(5)")

  • [position() > 2] becomes :gt(2)

$("p:gt(2)")

Custom Selectors

jQuery includes some expressions that aren't available in either CSS or XPath, but were found to be very handy, so were included.

The following expressions' syntax is based upon the various CSS selectors, of similar names.

Custom Selectors

  • :even Selects every other (even) element from the matched element set.
  • :odd Selects every other (odd) element from the matched element set.
  • :eq(0) and:nth(0) Selects the Nth element from the matched element set
  • :gt(N) Selects all matched elements whose index is greater than N.
  • :lt(N) Selects all matched elements whose index is less than N.
  • :first Equivalent to :eq(0)
  • :last Selects the last matched element.
  • :parent Selects all elements which have child elements (including text).
  • :contains('test') Selects all elements which contain the specified text.
  • :visible Selects all visible elements (this includes items that have a display of block or inline, a visibility of visible, and aren't form elements of type hidden)
  • :hidden Selects all hidden elements (this includes items that have a display of none, or a visibility of hidden, or are form elements of type hidden)

Some examples:

$("p:first").css("fontWeight","bold");

$("div:hidden").show();

$("/div:contains('test')", this).hide();

Form Selectors

There are a few selectors for form elements: