Thursday, April 28, 2011

how eq(0) works with DOM

Hi All,

I want to know in below case will the browser stop traversing the DOM after getting the first .myclass

   $(".myclass").eq(0)
From stackoverflow
  • No. In your example, the browser will fetch all the elements with class myclass. Then you apply a filter for the first element.

    You might be able to call .end() after your .eq(0) to get the whole elements back.

    You need the selector eq, like in the following example $(".myclass:eq(0)").

    Wondering : ok, thanks for ur inputs.
  • I don't believe so.

    $(".myclass")
    

    Will return a jQuery object that (behind the scenes) contains an array of all matching DOM elements.

    You are then calling a method on that object to return the first element.

    If you want to avoid this, you need your selector to only select one element. Take a look at the documentation for selectors:

    http://docs.jquery.com/Selectors

    Try this instead:

    $(".myclass:first").eq(0)
    
    Wondering : No i just wanted to know how it works.Thanks for the info.
    bobince : Note that in practice this will actually slow it down in recent browsers! This is because `:first` isn't a standard CSS selector, so jQuery won't be able to pass the work off the the new Selectors-API function `document.querySelectorAll`, and will have to fall back to the usual native-JavaScript ‘Sizzle’ selector library. The fastest solution would be to use `document.querySelector` (without the `All`) which gets just one element. However there is currently no jQuery integration for this method. You could sniff for it and fall back to jQuery, but it's probably a premature optimisation.
    SpoonMeiser : Does jQuery use this API now? In my experience, selecting by class (for large documents, at least) is slow anyway.

0 comments:

Post a Comment