views:

268

answers:

3

My problem is that I have a table, but I only want a subset of the rows, from first index to last index. I thought you could do it like this:

$('table tr:gt(2):lt(5)');

I thought it would give you only rows #3 and #4 but it ends up giving you more than that. How can I tell the selector to choose only rows #3 and #4?

A: 

I reckon you've got it spot on, although I would imagine that jQuery will count from 0 in it's index of elements.

So would it be gt(1) and lt(4) ?

DavidYell
Right, it's from the zero index. My mistake.
Bob
+2  A: 

How about $('table tr').slice(2, 4)

Since JavaScript arrays are 0 indexed, that will give you the third and fourth row of the table. Slice will still return a jQuery wrapped (sub)set, so it's the same end result.

Dave Ward
Yes, but I want the selector to only look for the specified rows. With that method, jQuery first fetches all of the table rows, then filters out the undesired tables.
Bob
@Bob, it does that even if you use the selector version
TM
Oh, that's disappointing. I assumed that internally jQuery would skip over rows that are less than the given index, or stop when the rows are greater than the given index when you use their respective selector modifiers. At least that way it wouldn't have to consider all of the table rows.
Bob
It's not much to worry about either way, since those rows are coming back from a relatively fast getElementsByTagName call. I *greatly* prefer using slice, because that complex :gt():lt() selector is just plain text and very brittle/unreadable.
Dave Ward
+2  A: 

You're pretty close, but the problem in your selector is the :lt(5) filter.

You would want something like:

$('table tr:gt(2):lt(2)');

The difference is that by the time the lt() filter is applied, the first three elements were already removed from the set (by the gt() filter). So this will grab the 3rd and 4th element (zero-indexed), instead of the 3rd through the 8th.

Alex Sexton
Perfect! This works as expected. Thanks for clarifying that.
Bob
I suppose as a side question where can I submit a feature request to add a range selector, so that it might look something like$('table tr:in(2,4)')or is there a plugin that already accomplishes such functionality?
Bob
@Bob you should really look into using `slice` as @DaveWard answered. it is a lot more readable and will work the way you expect it to. Also, you aren't getting any performance gains by doing things this way, it's still finding all `table tr` then filtering that list down.
TM
I agree that the best solution here would definitely be a slice, I was merely clarifying the code in question. Slice is definitely the best way to get a range. Filter selectors are much slower than native array functions.
Alex Sexton