The DOM structure is also a Tree structure. The Tree selector provided by jQuery can be used to select nodes in the DOM Tree. The tree selector methods include children (), parent (), parents (), next (), prev (), and siblings ().
Select "child"-children () for an element ()
Copy codeThe Code is as follows:
<Ul id = "parent">
<Li id = "son1"> first column </li>
<Li id = "son2"> second column </li>
<Li id = "son3"> third column </li>
</Ul>
$ ("# Parent"). children (). length // obtain the number of all "children" (li), "3"
$ ("# Parent"). children ("# son1"). text (); // obtain the value of the first "child" (li)-"first column"
Select "parent"-parent () for an element ()
Copy codeThe Code is as follows:
<Ul id = "parent">
<Li id = "son1"> first column </li>
<Li id = "son2"> second column </li>
<Li id = "son3"> third column </li>
</Ul>
$ ("# Son1"). parent (). attr ("id"); // obtain ul's ID-"parent"
Select an element's "ancestor"-parents () (Note: Select Level 1 and above until Copy codeThe Code is as follows:
<Div id = "grand">
<Ul id = "parent">
<Li id = "son1"> first column </li>
<Li id = "son2"> second column </li>
<Li id = "son3"> third column </li>
</Ul>
</Div>
$ ("# Son2"). parents (). each (function (I ){
If (I <3) // only display 3 generations of ancestor
Alert(%(this%.html ());
});
Select "younger brother"-next () of an element ()
Copy codeThe Code is as follows:
<Ul id = "parent">
<Li id = "son1"> first column </li>
<Li id = "son2"> second column </li>
<Li id = "son3"> third column </li>
</Ul>
$ ("# Son2"). next (). text (); // select # son3 select the "brother" of an element"
Prev ()
Copy codeThe Code is as follows:
<Ul id = "parent">
<Li id = "son1"> first column </li>
<Li id = "son2"> second column </li>
<Li id = "son3"> third column </li>
</Ul>
$ ("# Son2"). prev (). text (); // select # son1 select the "brother" of an element"
Siblings ()
Copy codeThe Code is as follows:
<Ul id = "parent">
<Li id = "son1"> first column </li>
<Li id = "son2"> second column </li>
<Li id = "son3"> third column </li>
</Ul>
$ ("# Son2"). siblings (). text (); // select # son1 and # son3