26
Jun
2012

How to select children elements in jQuery

Posted in: jQuery , No Comments

jquery_logo
We have already learned how to select CSS elements in jQuery in past post.
How to select CSS elements in jQuery
But that was very basic of selecting CSS elements in jQuery. Now let’s go little deeper in selecting CSS elements. In this tutorial I will show you how you can select only direct child elements of a CSS class / ID in jQuery.

Before I start, let’s clear what is direct child and indirect child elements.

<ul>
	<li>one - Direct child</li>
	<li>Two - Abother Direct child</li>
		<ul>
			<li>Three - Indirect child element</li>
		</ul>
	<li>Four - I am also direct child</li>
</ul>

From above example you can easily understand difference between direct child and indirect child element.

Now in jQuery, we want to select only direct child elements. So, let’s see how we can do this.
Step 1:
Write basic HTML code with some direct child and some undirect child elements.

<ul class="onlychild">
	<li>One - Direct child</li>
	<li>Two - Abother Direct child</li>
		<ul>
			<li>Three - Indirect child element</li>
		</ul>
	<li>Four - I am also direct child</li>
</ul>

At this stage our page looks like this. All li elements appear in black font color.

Step 2:
Add jQuery library in head section.

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

Step 3:
Now we will add jQuery code in head section and tell it to find all direct child elements of ul class onlychild and change its color to red.

<script type="text/javascript">
$(document).ready(function() {
$("ul.onlychild").children("li").css('color' , 'red');
});
</script>

Done!!!
So, it will look like this now:


You can see that only direct child elements color changed to red.

Select all child elements

If you want to select all child elements, use below code. In below code I will tell jQuery to find all child li elements of class onlychild and change its color to blue.

<script type="text/javascript">
$(document).ready(function() {
$("ul.onlychild").find("li").css('color' , 'blue');
});
</script>

You can see the change here.

About the Author

Name: Ravi Shekhar
I love learning and sharing web stuffs.

Share this post

Twitter Facebook Google Buzz Digg StumbleUpon Delicious Technorati

Leave a Reply