Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the first "n" items with jQuery

Tags:

jquery

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.

like image 601
Omiod Avatar asked Dec 08 '09 08:12

Omiod


People also ask

How do I get the first element of a list in jQuery?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).

Can you select multiple elements in jQuery?

In jQuery, you can select multiple elements by separate it with a comma “,” symbol. In above case, select all elements that have a class name of “class1” and “class2”, and id of “id1”.

What does $() do in jQuery?

$(document) wraps a jQuery instance around the document object. ( $ is just an alias for jQuery .)

How do I select something in jQuery?

The select() method is an inbuilt method in jQuery which is used when some letters or words are selected (or marked) in a text area or a text field. Syntax: $(selector). select(function);


2 Answers

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

$("a").slice(0,20) 
like image 123
istruble Avatar answered Sep 22 '22 05:09

istruble


Use lt pseudo selector:

$("a:lt(n)") 

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

like image 30
kgiannakakis Avatar answered Sep 23 '22 05:09

kgiannakakis