سؤال

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?

هل كانت مفيدة؟

المحلول

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);

نصائح أخرى

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.

try:

$('abc').children(":eq(0)")
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top