Traversal Methods in JQuery


In previous article, we looked into selectors available for accessing elements in DOM. In this article, we will focus on traversal methods followed by chaining.

JQuery provides traversal methods to navigate up, down with ease.  We will look into these methods with an example. Let's have a look at the below HTML file:
 
<html>
  <head>
    <title>JQuery Sample HTML Page</title>
<script src="jquery-1.4.2.min.js" type="text/javascript">
</script>
<script language="javascript" type="text/javascript">
    $(document).ready(function() {
    $('#row1').next().hide('slow'); // Here 2nd row will be hidden.
    $('#row1').parent().parent().attr('border''10'); //First parent is TBODY,Next is Table tag.
    $('#row1').siblings().css('color''blue'); // Here all siblings will be colored.
});
</script>
</head>
<body>
<table border="0">
    <tr id='row1'>
        <td>Row 1,Column 1</td>
        <td>Row 1,Column 2</td>
        <td>Row 1,Column 3</td>
    </tr>
    <tr>
        <td>Row 2,Column 1</td>
        <td>Row 2,Column 2</td>
        <td>Row 2,Column 3</td>
    </tr>
    <tr>
        <td>Row 3,Column 1</td>
        <td>Row 3,Column 2</td>
        <td>Row 3,Column 3</td>
    </tr>
</table>
</body>
</html>

In above HTML, parent() will return the parent of the element. We can use next(), prev() to move forward and backward in the DOM structure. We can use get() method to access DOM element's properties present in JQuery result set as shown below:

$('tr').get(0).innerHTML

(or)

$('tr')[0].innerHTML  // Array Index based syntax

For complete list of traversal methods, refer: http://api.jquery.com/category/traversing/.

Now, we will look into chaining in JQuery and its benefits. In JQuery ,  we can perform multiple operations on sets of elements in a single line of code. This will reduce the need of temporary variables and lines of code. But, code readability might be bad.

$('tr').first().css('color','red').end().last().css('color','green');

In above code, first row color will be changed to red than calling end() will revert back to result set having all tr's. So, calling end() will takes us back to older result set before filtering.

I am ending the things here. In next article, we will look into JQuery Events and its types. I hope this article will be helpful for all.

Up Next
    Ebook Download
    View all
    Learn
    View all