views:

29

answers:

3

I'm porting a webapp from prototype to jquery in which I often used the prototype Down() function. (selecting the first child of a given element)

Glancing over the JQuery-api one of the ways to do this would be:

prototype: $('abc').down(); jquery: $('abc').children().first();

However, since this first fetches all children and applies a filter aferwards, I doubt it's efficient for this use-case.

What's a better way?

A: 

try:

$('abc').children(":eq(0)")
Anatoly G
yup thanks. i'll accept when it let's me (9 minutes ;-)
Geert-Jan
so it seems $('abc').children(":eq(0)") is no different than what I used initially ($('form').children().first();) . I hoped to have some kind of selector that didn't need to know all children before returning the first one..
Geert-Jan
A: 

There are a couple ways you can do this.

First, this returns an array containing single element.

$('form').children().first(); 

Also note this is a more readable version of $('form').children(":eq(0)");

Second, this returns just the element extracted from the array

$('form').children()[0];

Or if you know what type of element your after (rather than just first child regardless of element type) you can use:

$('form').find("input:first");

Finally, if you don't strictly need the element relative to its parent, you can just access it directly using a CSS3 selector:

$("input:first");

I'd suspect that this last option is the most effiecent if you can get away with it. But if anyone has more to say about efficiency, I'd like to hear it.

Cory Schires
Regarding performance you can check this jsPerf test I just created: http://jsperf.com/jquery-get-first-child
Dan Manastireanu
+1  A: 
Dan Manastireanu
yeah, this looks good, thanx
Geert-Jan