Traversing in jQuery

By | October 1, 2022

jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in an HTML or XML document randomly as well as in sequential method. Elements in the DOM are organized into a tree-like data structure that can be traversed to navigate, locate the content within an HTML or XML document.

Document Object Model (DOM) – is a W3C (World Wide Web Consortium) standard that allows us to create, change, or remove elements from the HTML or XML documents.

The DOM tree can be imagined as a collection of nodes related to each other through parent-child and sibling-sibling relationships and the root start from the top parent which is HTML element in an HTML document.

Before we start traversing a DOM, Let’s understand the terminology of parentchild and sibling. Let’s see an example:

<body>
   <p>This is paragrah</p>

   <div><span>This is div</span></div>

   <button id="b1">Get width</button>
   <button id="b2">Set width</button>
</body>

In the above example, we have a <body> element at the top, which is called a parent for all the elements. The <div>, <p> and <button> elements inside the <body> element are called siblings. Again <span> element inside <div> is a child of <div> and <div> is called a parent of <span> element.

The <div> element is a next sibling of the <p> element and <p> is the previous sibling of the <div> element.

Traversing the DOM

Most of the DOM Traversal Methods do not modify the jQuery DOM object and they are used to filter out elements from a document based on given conditions. jQuery provides methods to traverse in the following three directions:

  • Traversing Upwards – This direction means traversing the ancestors (Parent, Grandparent, Great-grandparent etc.)
  • Traversing Downwards – This direction means traversing the descendants (Child, Grandchild, Great-grandchild etc.)
  • Sideways – This direction means traversing the ancestors the siblings (Brother, sisters available at the same level)

We will learn all the above traversing methods starting from the next chapter.

Leave a Reply

Your email address will not be published. Required fields are marked *