HTML and CSS Reference
In-Depth Information
Yet another variant on the same theme is the closest function. This allows us to find the
closest ancestor that matches a given selection criteria, starting with a specific set of nodes
in the initial selection. This first examines the selected node against the criteria, then works
its way up the DOM tree until it finds a match. For instance, if we want to find the closest
div to each label , we could use the following selection:
> $('label').closest('div')
Another example of a traversal function is returning the last element. As we have seen, a
pseudo-class on the selection itself also supports this. For instance, this returns the last row
in the tasks table:
> $('#tblTasks tr').last()
As with all traversal functions, the last function also supports a parameter representing se-
lection criteria allowing you to find the last element that meets specific criteria.
The traversal functions we have examined up until this point all return a new set of ele-
ments that typically do not include any of the elements from the original selection. In some
cases it is useful to retain the original selection while including additional elements found
during the traversal. For instance, suppose we had returned a set of input fields, and now
wish to also include all the labels in the result set. This can be achieved with the following:
> $('input').add('label')
A similar mechanism for achieving this is to augment any of the traversal functions above
with a request to also add the original elements. For instance, the following call will return
all labels and their closest div elements:
> $('label').closest('div').andSelf()
This particular line of code is a good time to introduce another important topic: chaining.
Due to the fact that most jQuery function calls return an array of elements, and most jQuery
function calls can be invoked on an array of elements, it is very easy to chain a set of func-
tion calls together, each acting on the elements returned by the call that preceded it. This
process can continue almost indefinitely, for instance:
> $('input').parents('div').last().siblings().children()
If we trace this through, it is doing the following:
1. Find all input elements.
2. Find any div elements that are parents of these elements.
3. Limit the result set to the last div element.
4. Find its siblings.
Search WWH ::

Custom Search