18
Jul
2012

How to select first and last child element in jQuery

Posted in: jQuery No Comments

jquery_logo
In this jQuery tutorial I will explain how to select first and last child element. This is very basic jQuery stuff but useful.

Step 1:
Write a basic HTML list elements

<ul class="list">
<li>Pellentesque habitant morbi tristique senectus et netus</li>
<li>Pellentesque habitant morbi tristique senectus et netus</li>
<li>Pellentesque habitant morbi tristique senectus et netus</li>
<li>Pellentesque habitant morbi tristique senectus et netus</li>
</ul>

Step 2:
Call jQuery library

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

Step 3:
Now we will add jQuery code in head section and tell it to find first list item of class list and change its color to red. And also find last list item of class list and change its color to blue.

<script type="text/javascript">
$(document).ready(function() {
  $(".list li:first").css('color', 'red');
  $(".list li:last").css('color', 'blue');
});
</script>

Done!!
Check live demo.

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