15
Aug
2012

How to select Even and Odd elements in jQuery

Posted in: jQuery No Comments

jquery_logo
In this tutorial we will learn how to select even and odd elements from a list, table etc. in jQuery

Step 1:
Prepare a list items under class listitems

<ul class="listitems">
	<li>First element</li>
	<li>Second element</li>
	<li>Third element</li>
	<li>Fourth element</li>
	<li>Fifth element</li>
	<li>Sixth element</li>

</ul>

Select all list items

Below jQuery code will select all list items under class listitems and change its color to red.

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

Select only even list items

Below jQuery code will select all even list items under class listitems and change its color to red.

<script type="text/javascript">
$(document).ready(function() {
$(".listitems li:even").css({color: 'red'});
});
</script>

Select only odd list items

Below jQuery code will select all odd list items under class listitems and change its color to red.

<script type="text/javascript">
$(document).ready(function() {
$(".listitems li:odd").css({color: 'red'});
});
</script>

Select Even and Odd list items

Below jQuery code will select all even list items under class listitems and change its color to red.
And will also select all odd list items under class listitems and change its color to green.

<script type="text/javascript">
$(document).ready(function() {
$(".listitems li:even").css({color: 'red'});
$(".listitems li:odd").css({color: 'green'});
});
</script>

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