Getting the First Object Returned by a jQuery Selector CodeUnit 04 MAR 2010

If for instance you have just used a jQuery selector to grab a whole lot of objects and now realize that in actual fact you only want to effect the first object that the selector returned to you, you can rest easy in the knowledge that jQuery as per usual has you covered.

Now jQuery 1.4 has gone and simplified the logic for us by supplying us with a function neatly named first(), which when in action looks something like this:


However, if you are not up and running on the 1.4 library just yet, there is an older way of doing this, using either the built in selector :first or by making use of the specific object selector function, namely eq().

Using the built in selector method, your code would look like this:

$(‘li :first’)

On the other hand, using the eq() function will leave you with this:

$(‘li’).eq(0) … (where 0 is basically the beginning index of the returned object array)

In any event, using either one of these three methods will result in jQuery returning only one object, namely the first object it encountered when applying the initial selector value.


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.