jQuery: Finding/Traversing Child and Descendant Elements
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, 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="main">
<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>
Using Children() Function:
To select all the children div elements within the 'main' , we can simply write:
$('#main').children('div')
.css("background", "red");
This will select 'sub1', 'sub2' and sub'3'.
Using Hierarchical Parent > Child Expression:
We can select all the children div elements within the 'main' selection using hierarchical expression as below:
$('#main > div')
.css("background", "red");
Using Find Function:
We can also use find function select all the children div elements by writing as below:
$('#main').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.
Read more...