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.

IndexDescription
:firstselects first element
:lastselects last element
:evenselect even elements (zero-indexed)
:oddselect 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

  1. Red
  2. Pink
  3. Blue
  4. 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

jQuery Index Selector

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.



Read more articles


General Knowledge



Learn Popular Language