foreyez foreyez - 6 months ago 9
HTML Question

Why jQuery less than selector doesn't work

I'm trying to use jquery :lt() selector in the website it ways
"Description: Select all elements at an index less than index within the matched set." https://api.jquery.com/lt-selector/

<table border="1">
<tr><td>row0</td></tr>
<tr><td>row1</td></tr>
<tr><td>row2</td></tr>
<tr><td>row3</td></tr>
<tr><td>row4</td></tr>
<tr><td>row5</td></tr>
<tr><td>row6</td></tr>
</table>


I'd like to select row3 and row4 so I tried:

$("table tr:gt(2):lt(5)").css('background','red');


But it doesn't seem to work, it selects row3,row4,row5,row6 any ideas?

https://jsfiddle.net/foreyez/v3ro64bf/

edit: this is not a duplicate. I'd like a solution to my specific question. how do I get row3 and row4.

Answer

The indexes for the :lt are those returned by the :gt. The :lt only has 4 elements fed into it, of which all of them have an index less than 5, so all of them are matched.

The first :gt effectively returns rows 3, 4, 5, and 6, and only those rows are matched against by the :lt.

If you want to select only rows 3 and 4, you want :gt(2):lt(2) to select the first two rows returned by :gt(2):

$("table tr:gt(2):lt(2)").css('background','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr><td>row0</td></tr>
<tr><td>row1</td></tr>
<tr><td>row2</td></tr>
<tr><td>row3</td></tr>
<tr><td>row4</td></tr>
<tr><td>row5</td></tr>
<tr><td>row6</td></tr>
</table>