This article describes the usage of hierarchical selectors in JQuery. Share it for your reference. The details are as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/"> <html xmlns="http:///1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Hierarchical selector</title> <script src="jquery-1.6." type="text/javascript"></script> <script type="text/javascript"> $(function () { //------1. Match all descendant elements under the given ancestor element //(Including child elements and elements of child elements, extending downwards) var $divs = $("#main div"); for (var i = 0; i < $; i++) { alert($(i).id); } //-----2. Match all child elements under the given parent element, including only direct child elements //(Sub-elements that do not contain child elements) var $divs = $("#main > div"); for (var i = 0; i < $; i++) { alert($(i).id); } //---- + next $("lable + input ") : Match all next elements immediately after prev //Note: You can only go to the first one, and it is next to each other. If it is not next to div1, you cannot get it. //......<1>.Example 1 var $divBrother = $("#div1 + div"); //Use #div1 ID selector, only div2 is obtained alert($(0).id); //...<2>.Example 2 var $divBrothers = $("div + div"); //Use the div tag selector, adjacent divs can be retrieved from divSun1 (adjacent to divSun), div2 (adjacent to div1) for (var i = 0; i < $; i++) { alert($(i).id); } //----- ~ siblins //$("form ~ input") : Match all siblings elements after the prev element //Note: The element after the match does not include this element. //And siblings matches elements of the same generation as prev, and their descendants are not matched. var $divBrothers = $("#main ~ div"); for (var i = 0; i < $; i++) { //Get main1, main2, main3 alert($(i).id); } } ); </script> </head> <body> <div > <div class="myDiv">I amdiv1 <div >I am孙子div <div >I am孙子的孙子div</div> </div> <div >I am孙子div</div> </div> <div class="myDiv">I amdiv2</div> </div> <div ></div> <div ></div> <input type="button" value="button" /> <div ></div> </body> </html>
For more information about jquery selector, please view the topic of this site:Summary of jquery selector usage》
I hope this article will be helpful to everyone's jQuery programming.