Finding and Traversing Child/decendant Elements in JQuery
Wednesday, June 24, 2009
To traverse or select child/descendant elements in jQuery, we can use , children() function or the find() function (Perhaps there are more methods to do this, but these are what I have been using). The difference among children and find functions is that children() only selects the immediate children from the given element, while find() function selects all the descendant elements within the given element.
Example:
Suppose we have we have the following in the document:
<div id="Technowise">
<div id="sub1">
<input id="input1" type="text">
<input id="input2'" type="text">
</div>
<div id="sub2">
<input id="input3" type="text">
<input id="input4'" type="text">
</div>
<div id="sub3">
<input id="input5" type="text">
<input id="input6'" type="text">
</div>
</div>
To select all the children div elements within the 'Technowise' , we can simply write:
$('#Technowise').children('div')
.css("background", "red");
This will select 'sub1', 'sub2' and sub'3'.
We can do the same selection using hierarchical expression as below:
$('#Technowise > div')
.css("background", "red");
Similarly, we can also use find function as below:
$('#Technowise').find("div")
.css("background", "red");
But you should note that find() function will find every child in the hierarchy of the parent (that is including all its grand children, and grand-grand children!). So if there are some other div elements within 'sub1', 'sub2' or 'sub3', even those elements will be selected. So be careful, and use them according to what you need.
Happy jQuerying! :) Read more...

