javascriptjqueryoptimizationfindfindfirst

How to optimize $.find().first()?


I need to retrieve the first element.

I do that with this code...

$(element).find('.x').first();

As much as I understand, that code...

  1. Retrieves all elements from element that matched .x,
  2. Removes unneeded elements;

Is there any better way to do it? Like $.findOne() or something?


Solution

  • As per jQuery docs:

    Because :first is a jQuery extension and not part of the CSS specification, queries using :first cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :first to select elements, first select the elements using a pure CSS selector, then use .filter(":first").

    So rewriting your selector to:

    $(element).find('.x').filter(":first")
    

    or (this one will give you direct descendants only and will be faster than .find, unless you're looking for nested elements too)

    $(element).children('.x').filter(":first")
    

    should give you better results.


    Update After valuable inputs from kingjiv and patrick dw (see comments), it does seem that these two are faster than .filter(':first') contrary to what the doc claims.

    $(element).find('.x').first();   // faster
    
    $($(element).find('.x')[0]);     // fastest