- In jQuery, traversing is used to select an HTML element or elements based on their relation to other HTML elements.
- Traversing process contains a number of steps which starts by one selection and go ahead until you traversed the required element.
- There are few terms which used in traversing in jQuery:
1 Ancestor: ancestor represents the parent, grandparent, great-grandparent and other such type of elements which has parental relation to the selected element.
2 Descendant: descendant represents the child, grandchild, great-grandchild and other such type of elements those are child of the selected elements in relation.
3 Sibling: siblings are the elements which has the same parents as selected element.
We can explain it in more easy way with the help of example given below.
In the above tree,
1 The <div> element is the parent of <h1> and both <p> elements and it is an ancestor of all elements inside it.
2 The left <p> element is the parent of <img> element and also child of <div> element.
3 The <h1> element is the parent of both <span> elements and also child of <div> element.
4 The right <p> element is the parent of <b> element and also the child of <div> element.
5 The <img> element is the child of left <p> element.
6 Both <span> elements are the children of <h1> element.
7 <b> element is the child of right <p> element.
8 Both <p> elements and <h1> are the siblings.
9 Both <span> elements are the siblings.
- To traverse the DOM model of any webpage, jQuery provides a large variety of methods.
- In jQuery, we used tree-traversal methods to make traversing easy and convenient.
<title> jQuery Example </title>
border:1px solid green;
$("span").parent().css("border","2px solid red");
$("p").children().css("border","2px solid green");
<h2> jQuery Traversing Example </h2>
<p><span> Hello Friends!!</span> <span> Welcome to CodingTag </span></p>
<button> Click Me! </button>
When you click the button,