English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
All elements in the HTML document can be easily accessed through the DOM tree
For example, the following methods can be used to access parent elements upwards
1.parent()The method can get the direct parent element of the specified element
$("span").parent(); gets the direct parent element of <span> element
2.parents()The method gets all parent elements of the given element
$("span").parents(); gets all parent elements of <span> element
$("span").parents(".text"); gets the element with class="text" in the parent element of <span> element
3.parentsUntil()The method gets elements between two given elements
$("span").parentsUntil(".text"); gets all elements between <span> and class="text" elements
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"> </script> <style> .container { float:left; margin-left:30px; } .container div { border:1px solid grey; margin:15px auto; } .ancestor1-1,.ancestor2-1,.ancestor3-1,.ancestor4-1 { width:150px; height:150px; } .ancestor1-2,.ancestor2-2,.ancestor3-2,.ancestor4-2 { width:120px; height:120px; } .ancestor1-3,.ancestor2-3,.ancestor3-3,.ancestor4-3 { width:90px; height:90px; } .now1,.now2,.now3,.now4 { width:60px; height:60px; } </style> <script> $(document).ready(function(){ $(".now1").parent().css("border-color","red"); $(".now2").parents().css("border-color","red"); $(".now3").parents(".ancestor3-2").css("border-color","red"); $(".now4").parentsUntil(".ancestor4-1").css("border-color","red"); } ); </script> </head> <body> <div> <div class="container"> <div class="ancestor1-1><div class="ancestor1-2><div class="ancestor1-3><div class="now1">Given Element</div></div></div></div> </div> <div class="container"> <div class="ancestor2-1><div class="ancestor2-2><div class="ancestor2-3><div class="now2">Given Element</div></div></div></div> </div> <div class="container"> <div class="ancestor3-1><div class="ancestor3-2><div class="ancestor3-3><div class="now3">Given Element</div></div></div></div> </div> <div class="container"> <div class="ancestor4-1><div class="ancestor4-2><div class="ancestor4-3><div class="now4">Given Element</div></div></div></div> </div> </div> </body> </html>
Illustration:
This simple method of jQuery traversal to the parent is all the content that the editor shares with everyone. I hope it can give you a reference, and I also hope everyone will support and cheer for the tutorial.