Question

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?

Was it helpful?

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.

OTHER TIPS

Alternatively:

$('whatever .foo .bar')

(or >.foo>.bar if you do want only direct children.)

As long as whatever is a standard CSS3 selector (not using any of the Sizzle-specific extensions), a single document-relative selector like the above will be passed off to document.querySelectorAll on modern browsers, which will be much faster than Sizzle's manual tree-walking.

[Whilst in theory it should be possible to use element.querySelectorAll to make queries of the form $(...).find(...) fast, jQuery currently won't use this method because of differences in opinion over how relative selectors are resolved between the Selectors-API standard and jQuery's traditional scoped behaviour.]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top