The jQuery :even selector selects the even elements of the matching tag name of HTML. The tag name elements can a table, list or any other group element.
Syntax
Let’s find out the way of using the selector with the syntax given below.
Use jQuery :even Selector to Select Even Rows of a Table
If you are using it for HTML table to add CSS to alternate even tr rows of a table. The jQuery :even selector selects the even tr rows starting from the even index(like 0, 2, 4, etc.).
See the below example to select the even rows of a table and add color to the text.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $( "table.mytable tr:even" ).css( "color", "red" ); }); }); </script> <style> .mytable{ border-collapse:collapse; } .mytable tr th, .mytable tr td{ border: 1px solid #ccc; } </style> <button type="button" class="mybtn">Click Me</button> <table class="mytable"> <tr> <th>Sr No</th> <th>Cricketer Name</th> <th>Score</th> </tr> <tr> <td>1</td> <td>Sanath Jayasuriya</td> <td>187*</td> </tr> <tr> <td>2</td> <td>Arjuna Ranatunga</td> <td>123</td> </tr> <tr> <td>3</td> <td>Mahela Jayawardana</td> <td>141*</td> </tr> </table> |
Output
Sr No | Cricketer Name | Score |
---|---|---|
1 | Sanath Jayasuriya | 187* |
2 | Arjuna Ranatunga | 123 |
3 | Mahela Jayawardana | 141* |
When you click the button given in the above example, it applies the red color to alternate even rows. This uses the jQuery :even selector to select the even tr to apply the color effect.
The above example selects the even tr elements of the table. However, you can also select the even list elements using the example given below.
Select Even List Element
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script> $(document).ready(function(){ $('.mylibtn').click(function(){ $( "ul.mylist li:even" ).css( "color", "red" ); }); }); </script> <button type="button" class="mylibtn">Click Me</button> <ul class="mylist"> <li>jQuery is the scripting langauge.</li> <li>You can apply sliding effect using jQuery.</li> <li>Create an animatio effect using jQuery.</li> <li>Add fading effect to an element with jQuery </li> <li>Select required element in a webpage and apply effect using jQuery.</li> </ul> |
Output
- jQuery is the scripting langauge.
- You can apply sliding effect using jQuery.
- Create an animatio effect using jQuery.
- Add fading effect to an element with jQuery
- Select required element in a webpage and apply effect using jQuery.
Click the button given in the example above to select the even list elements. It applies the red color to the list elements with indexes 0, 2 and 4.