Introduction to JQuery - Traversal Methods
Read: 2360 times    -     Avarage Rate: 3.7





2010 30 Mar

Welcome to this part of the introduction to jQuery series, after knowing how to use the JQuery Selectors let’s see how to use them. In this topic we’ll have a look on one of the powerful features of jQuery, the traversal methods. Let’s start by an example:

<html>
<head>
<title>JQuery Sample HTML Page</title>

<script src="jquery-1.4.1.js" type="text/javascript">
</script>

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#div3').next().hide('slow'); // Here div2 will be hidden.
$('#div2').parent().css('background-color', 'Aqua'); //div1 background will be aqua
$('#div3').siblings().css('color', 'Aqua'); // div3 sblings (div5) font color will be aqua
});
</script>

</head>
<body>
<div id="div1" style="background-color: Red; width: 400px; height: 300px;">
<div id="div2" style="background-color: green; width: 100px; height: 250px;">
<div id="div3" style="background-color: blue; width: 200px; height: 50px;">
DIV3
</div>
<div id="div4" style="background-color: Fuchsia; width: 200px; height: 50px;">
DIV4
<div id="div5" style="background-color: Olive; width: 30px; height: 30px;">
5
</div>
</div>
</div>
</div>
</body> 


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.

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.
Comments
1.

 Good One (Y) I Love JQuery !

2.

 Welcome Hassan, I love jQuery too !