Odd & Even Selectors in jQuery

Rating: 5 - 1 Votes

Odd & Even Selectors in jQuery

jqueryWhenever you select an element by Tag Name, it will return collection of elements which have the same Tag Name.  That collection always starts from 0.  We can manipulate those elements by their odd and even position in collection using Odd and Even selectors in jQuery.  We are going to use Tag Name and ID selectors along with it.

In the below given example, we have 2 tables.  One has the ID of table1 and another ID of table2.

With Tag Name Selector:  It will select all TR elements in the table and change the background color depending upon their odd and even position in collection.  The syntax for Odd selector is $(‘TagName:Odd’) and for Even selector is $(‘TagName:Even’).

With ID Selector:  It will select all TR elements in the table of ID table1 and change the background color depending upon their odd and even position in collection.  There will be no change in another table.  The syntax for Odd selector is $(‘#ElementID TagName:Odd’) and for Even selector is $(‘#ElementID TagName:Even’).