tags:

views:

99

answers:

4

With Jquery, I need to select just the first "n" items from the page, for example the first 20 links instead of selecting all of them with the usual

$("a")

Sounds simple but the jQuery manual has no evidence of something like this.

+3  A: 

Use lt pseudo selector:

$("a:lt(n)")

This matches the elements before the nth one (the nth element excluded). Numbering starts from 0.

kgiannakakis
A: 
$("a:lt(n)")

JQuery Documentation

hsz
+1  A: 

Try the :lt selector: http://docs.jquery.com/Selectors/lt#index

$('a:lt(20)');
David
+4  A: 

You probably want to read up on slice. You code will something like this:

$("a").slice(0,20)
istruble
Though the `:lt(20)` approach looks much cleaner, using slice is *much* more efficient if you have a large result set to start with. Unfortunately, when evaluating ":lt" and other positional selectors, **jQuery loops through the entire set**, even if it's just getting the first element. I've written more about this on my blog here: http://spadgos.com/?p=51
nickf
oh, and here's a demonstration of what i'm talking about, this time with graphs: http://fisher.spadgos.com/jquery/jquery-first-vs-eq.html
nickf
Thank you, a side requirement of my request was about performances, so this the right answer for me.Thanks to the others for pointing out the :lt selector too.
UVL