Search code examples
jqueryjquery-selectorsperformancedom-traversal

jquery parent descendant selector


Why is 1 faster than 2?

  1. $('#p1').find('span');
  2. $('#p1 span');

Solution

  • In jQuery 1.4 the selector is checked if it is an id selector (like your #p1).

    • If it indeed is, the document.getElementId(...) is called and result is wrapped in jQuery utility object and returned.
    • If it is anything other than that, jQuery calls Sizzle which then does whatever it does to find the elements. And, judging from the source, this is pretty non-trivial stuff.