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.
link Parents
The methods for finding the parents from a selection include .parent()
, .parents()
, .parentsUntil()
, and .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
26
|
|
link Children
The methods for finding child elements from a selection include .children()
and .find()
. The difference between these methods lies in how far into the child structure the selection is made. .children()
only operates on direct child nodes, while .find()
can traverse recursively into children, children of those children, and so on.
1
2
3
4
5
6
7
8
9
|
|
link 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 .prev()
, next elements with .next()
, and both with .siblings()
. There are also a few other methods that build onto these basic methods: .nextAll()
, .nextUntil()
, .prevAll()
and .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
28
29
30
31
|
|
Use .siblings()
to select all siblings:
1
2
3
4
5
6
7
|
|
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.