02.06.2013 Views

DOM Traversal Methods

DOM Traversal Methods

DOM Traversal Methods

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

[ 39 ]<br />

Chapter 3<br />

Selector Context<br />

By default, selectors perform their searches within the <strong>DOM</strong> starting at the document<br />

root. However, an alternative context can be given for the search by using the<br />

optional second parameter to the $() function. For example, if within a callback<br />

function we wish to do a search for an element, we can restrict that search:<br />

$('div.foo').click(function() {<br />

$('span', this).addClass('bar');<br />

});<br />

Since we've restricted the span selector to the context of this, only spans within the<br />

clicked element will get the additional class.<br />

Selector context is also useful for XML documents, as they do not form part of the<br />

default <strong>DOM</strong> tree. For example, if an AJAX call has returned an XML structure in the<br />

variable data, then we can perform searches within that structure:<br />

$('//foo/bar', data)<br />

Internally, selector context is implemented with the .find method, so $(selector,<br />

context) is equivalent to $(context).find(selector).<br />

While the jQuery API only specifies <strong>DOM</strong> elements, arrays of <strong>DOM</strong><br />

elements, and jQuery objects as valid contexts, in practice selectors and<br />

HTML snippets can be used here as well.<br />

Wrapping <strong>DOM</strong> elements<br />

The second and third formulations of this function allow us to create a jQuery object<br />

using a <strong>DOM</strong> element or elements that we have already found in some other way.<br />

A common use of this facility is to perform jQuery methods on an element that has<br />

been passed to a callback function in the keyword this:<br />

$('div.foo').click(function() {<br />

$(this).slideUp();<br />

});<br />

This example causes elements to be hidden with a sliding animation when clicked.<br />

An element must be wrapped in a jQuery object before we call jQuery methods on<br />

it because the handler receives the clicked item in the keyword this as a bare<br />

<strong>DOM</strong> element.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!