views:

34

answers:

1

Say I have an arbitrary number children (e.g. "td"s) of a given element (e.g. a "tr"), and I need to grab a given number of these (say, 4) at a given position (say, 3; td's 3 - 67, in this case). What would the best query for doing this look like?

Note that I could be dealing with a potentially thousands of children, so I'd like to not be slicing up arrays in the thousands on a routine basis.

Edit: It doesn't have to go through jQuery, if there's a more efficient option that goes straight to the DOM...

+6  A: 

You can use .slice() for this, for example:

$("tr td").slice(2, 7)
//of if you have the <tr>
$(this).children("td").slice(2, 7)

The above would get the 3rd through 7th <td>, since it's a 0-based index. Or the jQuery-less version, say you have the <tr> DOM element:

var tds = tr.getElementsByTagName("td");
for(var i = 2; i<7; i++) {
  //do something
}

You can test both versions here.

Nick Craver
*Works*, but I was hoping for something a bit more efficient than that...
Hamster
@Hamster Do you know that it's not fast enough? Have you profiled?
kevingessner
Oh wait, this isn't array slice we're talking about?
Hamster
@Hamster - Yup, I added a non-jQuery version as well in case that's what you're after...I assumed based on tags you were after the jQuery selector version.
Nick Craver
Well what I'm after is a way to grab subsets quickly, as I'm dealing with potentially thousands of child elements (not table columns or rows, necessarily), and I'd like not be rebuilding arrays to slice up each time.
Hamster
@Hamster - You *have* to iterate over them to get them one way or another, such is the nature of the DOM, not really sure how to give you a more efficient way than the above. Remember you're creating an array (or node list) of *references*, not actual copies of the elements.
Nick Craver
And the only way to get them is by calling getters that build array copies? I mean, I GUESS I could cache the gotten arrays, but if the DOM changes...
Hamster
@Hamster - The javascript only solution doesn't build an array, it iterates over the node lists at the time of execution, always discarding the result...if you wanted to cache it you certainly could.
Nick Craver