Traversing
Once you've made an initial selection with jQuery, you can traverse deeper into what was just selected. Traversing can be broken down into three basic parts: parents, children, and siblings. jQuery has an abundance of easy-to-use methods for all these parts. Notice that each of these methods can optionally be passed string selectors, and some can also take another jQuery object in order to filter your selection down. Pay attention and refer to the API documentation on traversing to know what variation of arguments you have available.
Parents
The methods for finding the parents from a selection include $.fn.parent()
, $.fn.parents()
, $.fn.parentsUntil()
, and $.fn.closest()
.
1
2
3
4
5
6
7
8
9
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
|
Children
The methods for finding child elements from a selection include $.fn.children()
and $.fn.find()
. The difference between these methods lies in how far into the child structure the selection is made. $.fn.children()
only operates on direct child nodes, while $.fn.find()
can traverse recursively into children, children of those children, and so on.
1
2
3
4
5
6
7
8
9
|
|
Siblings
The rest of the traversal methods within jQuery all deal with finding sibling selections. There are a few basic methods as far as the direction of traversal is concerned. You can find previous elements with $.fn.prev()
, next elements with $.fn.next()
, and both with $.fn.siblings()
. There are also a few other methods that build onto these basic methods: $.fn.nextAll()
, $.fn.nextUntil()
, $.fn.prevAll()
and $.fn.prevUntil()
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
|
Use $.fn.siblings()
to select all siblings:
1
2
3
4
5
6
|
|
See the complete documentation for these methods and more at Traversal documentation on api.jquery.com.
Be cautious when traversing long distances in documents — complex traversal makes it imperative that the document's structure remain the same, which is difficult to guarantee even if you're the one creating the whole application from server to client. One- or two-step traversal is fine, but it's best to avoid traversals that go from one container to another.