Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery index and selectors :lt and :gt

How do the selectors lt and gt work?? Is the same the order they are put? (if they are both in the same selector)

I need two answers for this question.

1) The result of the following line shouldn't ALWAYS be 0??? I'm asking those td wich index be greater than 3 AND lower than 2. There is index that could be: ix > 3 & ix < 2 at the same time!!

$("tr").find("td:gt(3):lt(2)").length

2) It turns out that when I change the order of the selectors gt and lt it starts working good. The result of the following line is 0.

$("tr").find("td:lt(2):gt(3)").length

Shoudn't the order of the selectors be indiferent to the result?

It is like if selector lt wont work if it is after a gt or something like that!

Additional info:

  • You can watch this here: http://jsfiddle.net/YQtRh/
  • For those who wonder what is the result of the first js line is 1.
  • In the example that td returned by the first line is the last one (.text() == 4)

Thanks!

Diego

like image 747
Diego Avatar asked Nov 17 '10 14:11

Diego


2 Answers

The issue is that jQuery runs its selectors sequentially, rather than compiling them into one selector. So :gt(3):lt(2) means "find all the elements in the set with an index of more than 3, then, in the returned set, find all elements with an index less than 2". Turning it round td:lt(2):gt(3) changes the order of the logic, so gives a different result.


In your example:

<table>
    <tr>
        <td>0</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
</table>

:gt(3) gives only the final element because it is the only one with an index greater than 3. So you have the following selection (from the Chrome console):

[<td>​4​</td>​]

Running :lt(2) on that obviously will have no effect, because the one element in the set has an index of 0, which is below 2.

Doing :lt(2) on the original set gives the following result:

[<td>​0​</td>​, <td>​1​</td>​]

Running :gt(3) on this will obviously remove all the elements from the set, because they have the indexes 0 and 1 respectively, neither of which is greater than 3.

like image 52
lonesomeday Avatar answered Oct 07 '22 13:10

lonesomeday


The indexes are re-indexed after a first filtering, this is sequential.

1) Imagine your td contains 5 elements.

  • Get indexes > 3 : Get 1 element.
  • Get indexes < 2 : Get 1 element cause the previous element of index 4 is now index 0.

2) In this case

  • Get indexes < 2 : Get a maximum of 2 elements.
  • Get indexes > 3 on a set of 2 elements or less : always returns 0.
like image 22
Jean-Bernard Jansen Avatar answered Oct 07 '22 15:10

Jean-Bernard Jansen