Jquery equivalent prototypes Down () - function

I am migrating a webapp from a prototype to jquery, in which I often used the prototype function Down (). (select the first child of this element)

Taking a look at jQuery-api, one way to do this is:

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

However, since this first selects all children and applies the filter, I doubt that it is effective for this use case.

What is the best way?

+5
source share
3 answers

You can extend jQuery and add a function down()as follows:

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

Thus, you do not need to change anything in the code.

jsFiddle.
jsPerf.
, , , ( 40% 70% ).

EDIT:
, . ( 25%)

(function($) {
  $.fn.down = function() {
    var el = this[0] && this[0].firstChild;
    while (el && el.nodeType != 1)
      el = el.nextSibling;
    return $(el);
  };
})(jQuery);
+6

.

, .

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

, $('form').children(":eq(0)");

-, ,

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

, , ( , ), :

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

, , CSS3:

$("input:first");

, , . - , .

+2

to try:

$('abc').children(":eq(0)")
+1
source

All Articles