Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery-equivalent to prototypes Down()-function

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?

like image 517
Geert-Jan Avatar asked Oct 21 '10 16:10

Geert-Jan


3 Answers

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);
like image 152
Dan Manastireanu Avatar answered Oct 17 '22 21:10

Dan Manastireanu


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.

like image 21
Cory Schires Avatar answered Oct 17 '22 21:10

Cory Schires


try:

$('abc').children(":eq(0)")
like image 1
Anatoly G Avatar answered Oct 17 '22 22:10

Anatoly G