CodingBison

jQuery provides various handy methods for navigating (traversing) the DOM tree. Before we do anything else, let us begin by listing some of the traversal methods:


Table: Methods for Traversing the DOM tree
MethodTraverses to
.parent()the parent node of the element (or elements)
.parents()all ancestors of the element (or elements)
.children()all child nodes that match the selector
.siblings()all sibling nodes of the element (or elements)
.next()the next sibling of the element (or elements)
.nextAll()all next sibling of the element (or elements)
.nextUntil()all next sibling nodes until the sibling nodes with specified selector
.prev()the previous sibling of the element (or elements)
.prevAll()all previous sibling of the element or elements)
.prevUntil()all previous sibling nodes starting at the sibling nodes with specified selector

To better describe these methods, let us use an HTML page as a basis. The example (provided below) consists of an ordered list that holds three list items.

 <!doctype html>
 <html>
 <body>
 <ol>
     <li id="idPhys" class="twoTimesWinner">Marie Curie</li>
     <li id="idChem" class="twoTimesWinner">Marie Curie</li>
     <li id="idPeace">Mother Teresa</li>
 </ol>
 </body>
 </html>

We can get a handle of the immediate parent node of the element or the elements. Thus, in the above HTML, $("#idChem").parent() would return the parent of the $("#idChem") element. That node would be the $("ol") node since it is this node that houses the list element with CSS id "idChem".

The .parents() method is more inclusive and it gives us a list containing all the ancestor nodes of the element or the elements that match the passed selector criteria. If we do not specify any selector, then it selects all ancestors. This method starts at the parent of the current element invoking it and then, traverses upwards. Thus, $("ol").parents() would return a list of two elements: $("body") and $("html").

The .children() method returns a list of all immediate child nodes that match the passed selector criteria. If we do not specify any selector, then it selects all child nodes. Once we have the returned list, we can traverse all the children by simply going through the elements of the returned list. Accordingly, $("body").children("ol") will return all the <ol> nodes that are immediate child nodes of the $("body") element.

The .siblings() method returns a list that contains all the siblings of the current element. This method also accepts an optional selector criteria and in that case, it will return only those sibling nodes that match the criteria. Thus, $("#idPhys").siblings() would retrieve the list element with the CSS id "idPhys" and then return all of its siblings.

The .next() method returns the immediate next sibling of the current element. In the above example, $("#idPhys").next() would return the $("#idChem") element. On the other hand, the .nextAll() method returns a list of all siblings that are present after the current element or the elements. We can also optionally provide a selector -- in that case, .nextAll() would return a list of all the siblings that are present after the current element that match the passed selector criteria.

The .nextUntil() method returns a list of all siblings that are present after the current element and are present before the (following) sibling that matches the passed selector criteria. Thus, it does not include the sibling that matches the passed selector criteria.

Unlike the .next() method, the .prev() method returns the immediate previous sibling of the current element. Thus, in the above example, $("#idChem").prev() would return the $("#idPhys") element. The .prevAll() method returns a list of all the preceding siblings; that is, those sibling nodes that are present before the current element or the elements. We can also optionally provide a selector and in that case, .prevAll() would return a list of all the siblings that are present before the current element that match the passed selector criteria.

The .prevUntil() method returns a list of all siblings that are present before the current element and are present after the preceding sibling that matches the passed selector criteria. Thus, it does not include the sibling that matches the passed selector criteria.

While we are at it, let us look at three examples to enhance our understand of the above methods.

The first example provides use-case of the following traversal methods: .parent(), .parents(), .children(), and .siblings(). For the sake of displaying, we also adds CSS id to various elements so that we can display the node using the .attr("id") method -- normally, there would be no need to assign CSS IDs to some of the elements like head, body, etc!

 <!doctype html>
 <html id="idHtml">
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <body id="idBody">
 <div id="idTitle">Nobel Laureates:</div>
 <ol id="idOl">
     <li id="idRutherford"> Ernest Rutherford (Chemistry, 1908)</li>
     <li id="idMunro">      Alice Munro (Literature, 2013)</li>
     <li id="idAward1AndAward2"><div>Nobel Laureates who won the Prize twice:</div>
         <ul id="idUl">
             <li id="idCuriePhys">  Marie Curie (Physics, 1903)</li>
             <li id="idCurieChem">  Marie Curie (Chemistry, 1911)</li>
         </ul>
     </li>
 </ol>

 <script type="text/javascript" id="idScript">
  $(document).ready(function() {
     // Get the parent of the <li> element with ID "idCuriePhys".
     var str = '$("#idCuriePhys").parent(): ' +  $("#idCuriePhys").parent().attr("id") + "<br>";

     // Get the parent of the parent of the <li> element with ID "idCuriePhys".
     str += '$("#idCuriePhys").parent().parent(): ' +  $("#idCuriePhys").parent().parent().attr("id"); 

     // Get all parents of the <li> element with ID "idCuriePhys".
     str += "<br>";
     $("#idCuriePhys").parents().each(function(indx, elem) {
         str += '<br>$("#idCuriePhys").parents(): ' +  $(elem).attr("id");
     });

     // Get all children of the <li> element with class "classUl".
     str += "<br>";
     $("#idUl").children().each(function(indx, elem) {
         str += '<br>$("#idUl").children(): ' +  $(elem).attr("id");
     });

     // Get all children of the element with ID "idTitle".
     str += "<br>";
     $("#idTitle").siblings().each(function(indx, elem) {
         str += '<br>$("#idTitle").siblings(): ' +  $(elem).attr("id");
     });

     // Append the text to the body element. 
     $("body").append(str);
  });
 </script>
 </body>
 </html>



Figure: Traversing Parent, Child, and Sibling nodes using jQuery Methods

The earlier example focused on parents, children, and siblings. Our second example deals with the .next() method and its variants.

 <!doctype html>
 <html>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <body>
 <div id="idTitle">Nobel Laureates:</div>
 <ol>
     <li id="idCuriePhys">  Marie Curie (Physics, 1903)</li>
     <li id="idRutherford"> Ernest Rutherford (Chemistry, 1908)</li>
     <li id="idCurieChem">  Marie Curie (Chemistry, 1911)</li>
     <li id="idMunro">      Alice Munro (Literature, 2013)</li>
 </ol>

 <script type="text/javascript">
 $(document).ready(function() {
     // Get the next() sibling of the <li> element with ID "idCuriePhys".
     var str = '$("#idCuriePhys").next(): ' +  $("#idCuriePhys").next().attr("id") + "<br>";

     // Get the next() of the next() sibling of the <li> element with ID "idCuriePhys".
     str += '$("#idCuriePhys").next().next(): ' +  $("#idCuriePhys").next().next().attr("id") + "<br>";

     // Get all next() siblings of the <li> element with ID "idCuriePhys".
     $("#idCuriePhys").nextAll().each(function(indx, elem) {
         str += '<br>$("#idCuriePhys").nextAll(): ' +  $(elem).attr("id");
     });

     // Get all next() siblings of the <li> element with ID "idCuriePhys" until the one with "idMunro".
     str += "<br>";
     $("#idCuriePhys").nextUntil("#idMunro").each(function(indx, elem) {
         str += '<br>$("#idCuriePhys").nextUntil("#idMunro"): ' +  $(elem).attr("id");
     });

     // Append the text to the body element. 
     $("body").append(str);
 });
 </script>
 </body>
 </html>

When we load the page, we would see the following text output from the script. As we discussed earlier, the .nextUntil() does not return the starting element, in this case, "#idCuriePhys"



Figure: Traversing DOM using jQuery's .next()-related Methods

Our third and last example demonstrates the .prev() method and its variants.

 <!doctype html>
 <html>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <body>
 <div id="idTitle">Nobel Laureates:</div>
 <ol>
     <li id="idCuriePhys">  Marie Curie (Physics, 1903)</li>
     <li id="idRutherford"> Ernest Rutherford (Chemistry, 1908)</li>
     <li id="idCurieChem">  Marie Curie (Chemistry, 1911)</li>
     <li id="idMunro">      Alice Munro (Literature, 2013)</li>
 </ol>

 <script type="text/javascript">
 $(document).ready(function() {
     // Get the prev() sibling of the <li> element with ID "idMunro".
     var str = '$("#idMunro").prev(): ' +  $("#idMunro").prev().attr("id") + "<br>";

     // Get the prev() of the prev() sibling of the <li> element with ID "idMunro".
     str += '$("#idMunro").prev().prev(): ' +  $("#idMunro").prev().prev().attr("id") + "<br>";

     // Get all prev() siblings of the <li> element with ID "idMunro".
     $("#idMunro").prevAll().each(function(indx, elem) {
         str += '<br>$("#idMunro").prevAll(): ' +  $(elem).attr("id");
     });

     // Get all prev() siblings of the <li> element with ID "idMunro" until the one with "idCuriePhys".
     str += "<br>";
     $("#idMunro").prevUntil("#idCuriePhys").each(function(indx, elem) {
         str += '<br>$("#idMunro").prevUntil("#idCuriePhys"): ' +  $(elem).attr("id");
     });

     // Append the text to the body element. 
     $("body").append(str);
 });
 </script>
 </body>
 </html>

When we load the page, we would see the following text output in the browser. As we discussed earlier, the .prevUntil() does not return the starting element -- in this case, "#idMunro"



Figure: Traversing DOM using jQuery's .prev()-related Methods





comments powered by Disqus