jQuery - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

jQuery Traversing

jQuery Traversing

shape Description

jQuery Traversing, which means "pass through", offers a various in-built methods which selects or finds the HTML elements using their relation to other elements.Using jQuery DOM tree can be traversed in order to find the parents,children, and other nearby elements of any selected element on the page. In DOM (Document Object Model) with HTML document, every element is related to other elements with some kind of relation. One can move easily up the DOM tree it could be the ancestors , and can move easily down the DOM tree it could be the descendants or can move easily sideways it could be the sibling of another element. jQuery traversing allows to move through different elements making use of their relations.

jQuery Ancestors

shape Description

With the help of jQuery, it is easy to move up the DOM tree to find the ancestors of an element. See below some of the methods used to find the ancestors of an element. [html] <html> <head> <title>jQuery Traversing</title> </head> <body> <div>div(great-grandparent) <ul>ul (grandparent) <li> li (direct parent) <span>span(current element)</span> </li> </ul> </div> </body> </html> [/html] [javascript] $(document).ready(function(){ $("span").parent().css({"color":"red","border": "2px solid red" }); }); [/javascript] Output:

jQuery Descendants

shape Description

With the help of jQuery,it is easy to move easily down the DOM tree to find the descendants of an element. See below some of the methods used to find the descendants of an element. [html] <html> <head> <title>jQuery Traversing</title> </head> <body> <div>div(current element) <ul>ul (child) <li> li(grandchild) <span>span(great grandchild)</span> </li> </ul> </div> </body> </html> [/html] [javascript] $(document).ready(function(){ $("div").children().css({"color":"red","border": "2px solid red" }); }); [/javascript] Output:

jQuery Siblings

shape Description

With the help of jQuery, one can move sideways to find the siblings of an element with in the same parent. See below some of the methods used to find the siblings of an element. Output:

Summary

shape Key Points

  • jQuery ancestors is a parent, grandparent, great-grandparent and so on.
  • jQuery descendants is child, grandchild, great-grandchild and so on.
  • jQuery Siblings move easily sideways.