jQuery Index Selector
Sometime, we need to select elements based on an order with other elements.
These are the filters in jQuery to select elements based on their order.
Index | Description |
:first | selects first element |
:last | selects last element |
:even | select even elements (zero-indexed) |
:odd | select odd elements (zero-indexed) |
:eq(n) | selects a single element by given index (n) |
:lt(n) | select all elements with an index less than n |
:gt(n) | select all elements with an index greater than n |
Example
<ol>
<li>Red</li>
<li>Pink</li>
<li>Blue</li>
<li>Green</li>
</ol>
<script>
$(document).ready(function(){
$('ol li:first').css("color", "red");
$('ol li:eq(2)').css("color", "blue");
$('ol li:odd').css("color", "pink");
$('ol li:last').css("color", "green");
});
</script>
Output of the above code
- Red
- Pink
- Blue
- Green
Example
<table border="1">
<tr>
<td>Cat</td>
</tr>
<tr>
<td>Dog</td>
</tr>
<tr>
<td>Elephant</td>
</tr>
<tr>
<td>Goat</td>
</tr>
<tr>
<td>Fox</td>
</tr>
</table>
<script>
$(document).ready(function(){
$("td:eq( 2 )").css("color", "red");
$("td:lt( 2 )").css("color", "blue");
$("td:gt( 2 )").css("color", "pink");
});
</script>
Output of the above code
In the above example, eq( 2 ) selects the first td element from the zero based index and sets the element color to red. lt( 2 ) select all elements less than index 2 and sets color to blue and gt( 2 ) select all elements greater than index 2 and sets color to pink.