JQuery-equivalent to prototypes Down()-function
Asked Answered
P

3

5

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?

Perrault answered 21/10, 2010 at 16:7 Comment(0)
E
6

You can extend jQuery, and add a down() function like this:

(function($) {
  $.fn.down = function() {
    return $(this[0] && this[0].children && this[0].children[0]);
  };
})(jQuery);

This way you don't have to change anything in your code.

You can see this live jsFiddle example.
Also you can view a performance comparisson in jsPerf.
It shows that this is faster than the methods presented in the other answers (which are from 40% to 70% slower).

EDIT:
An alternative version adapted from the actual prototype implementation. This is even faster (by 25%)

(function($) {
  $.fn.down = function() {
    var el = this[0] && this[0].firstChild;
    while (el && el.nodeType != 1)
      el = el.nextSibling;
    return $(el);
  };
})(jQuery);
Evelunn answered 21/10, 2010 at 17:13 Comment(0)
H
2

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.

Hurdle answered 21/10, 2010 at 16:27 Comment(1)
Regarding performance you can check this jsPerf test I just created: jsperf.com/jquery-get-first-childEvelunn
M
1

try:

$('abc').children(":eq(0)")
Majewski answered 21/10, 2010 at 16:9 Comment(1)
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..Perrault

© 2022 - 2024 — McMap. All rights reserved.