Search code examples
jquerydom-traversal

Should I use .find(".foo .bar") or .children(".foo").children(".bar")?


When using jQuery for DOM traversal both of these return the same results (I believe):

$("whatever").find(".foo .bar")
$("whatever").children(".foo").children(".bar")

Which is preferable to use?


Solution

  • They are not equivalent, as I'll explain below, but if adjust them to match, .children() for speed, .find() for brevity (extra work inside Sizzle, parsing this for starters), you decide which is more important.

    The first has different results, but if you know they're children, you can do this:

    $("whatever").find("> .foo > .bar")
    //equal to...
    $("whatever").children(".foo").children(".bar")
    

    This would be equivalent to your second function. Currently, the first as you have it would find this:

    <whatever>
      <div class="foo">
        <span>
         <b class="bar">Found me!</b>
        </span>
      </div>
    </whatever>
    

    The second would not, it requires that .foo be a direct child of whatever and .bar be a direct child of that, the .find(".foo .bar") allows them to be any level deep, as long as .bar in a descendant of .foo.