开发者

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").开发者_JAVA百科children(".foo").children(".bar")

Which is preferable to use?


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.


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.]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜