Chaining jQuery selectors :lt and :gt

有些话、适合烂在心里 提交于 2019-11-27 13:38:26

They're applied sequentially, so first you will filter away the first four elements (:gt(3)), then you will filter away all elements after the sixth (:lt(6)) element of the already filtered set.

Imagine this HTML:

<br/><br/>
<br/><br/>
<br/><br/>
<br/><br/>
<br/><br/>
<br/><br/>

Then do the following jQuery:

$('br:gt(3):lt(6)').addClass('sel');

You will now have:

<br/><br/>
<br/><br/>
<br class="sel"/><br class="sel"/>
<br class="sel"/><br class="sel"/>
<br class="sel"/><br class="sel"/>
<br/><br/>
ScottE

I suggest you use the slice() method instead.

http://docs.jquery.com/Traversing/slice#startend

$('table tr').slice(2, 5).addClass("something");

Not quite what you might think-

Working Demo

Basically, the second filter is applied sequentially, to the matched set of the first filter.

For example, on a table with 10 rows, :gt(3) will filter to elements 5 - 10, then :lt(6) will be applied to the 6 elements, not filtering any.

if you add /edit to the demo URL, you can play with the selector and see for yourself. If you change the second filter to :lt(2), you get rows 5 and 6 highlighted in red

For some reason :lt(6) will be ignored in that selection, so it will return everything greater than 3 in this intsance.

However, if you switch it over, it will work as expected

$('table tr:lt(6):gt(3)')

will return 2 rows (only row 4 and 5 is between 6 and 3).

**edit:**using v.1.3.2

And also, lt(6) isn't ignored, not just working as I expected it to. So :gt(3):lt(6) will in fact return 6 elements (if you have enough rows, that is)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!