jQuery traversa...LOGIN

jQuery traversal

What is traversal?

jQuery traversal, meaning "move", is used to "find" (or select) HTML elements based on their relationship to other elements. Start with a selection and move along this selection until you reach your desired element.

The picture below shows a family tree. With jQuery traversal, you can easily move up (ancestors), down (descendants), and horizontally (siblings) in the family tree, starting from the selected (current) element. This movement is called traversing the DOM.

img_travtree.png

##Illustration analysis:

  • The <div> element is the parent element of <ul> and all the content within it. ancestors.

  • The <ul> element is the parent element of the <li> element and is the child element of <div>

  • on the left The <li> element is the parent element of <span>, the child element of <ul>, and the descendant of <div>.

  • The <span> element is a child of <li> and a descendant of both <ul> and <div>.

  • Two <li> elements are siblings (have the same parent element).

  • The <li> element on the right is the parent element of <b>, the child element of <ul>, and is the descendant of <div>.

  • The<b> element is a child of the <li> on the right and is a descendant of both <ul> and <div>.




## Ancestors are father, grandfather, great-grandfather, etc. Descendants are children, grandchildren, great-grandchildren, etc. Siblings share the same parent.


jQuery provides a variety of methods for traversing the DOM.

The largest type of traversal method is tree traversal (tree-traversal).

The next chapter will explain how to move up, down, and at the same level in the DOM tree.


Next Section

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .ancestors * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("span").parent().css({"color":"red","border":"2px solid red"}); }); </script> </head> <body> <div class="ancestors"> <div style="width:300px;">div (曾祖父元素) <ul>ul (祖父元素) <li>li (父元素) <span>span</span> </li> </ul> </div> <div style="width:300px;">div (祖父元素) <p>p (父元素) <span>span</span> </p> </div> </div> </body> </html>
submitReset Code
ChapterCourseware