Should I use .find (". Foo.bar") or .children (". Foo"). Children (". Bar")?

When using jQuery to traverse the DOM, both of them return the same results (I believe):

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

Which is preferable to use?

+4
source share
2 answers

They are not equivalent, as I will explain below, but if they drive them, .children() for speed, .find() for short (additional work inside Sizzle, parsing this for starters), you decide which is more important.

The former have different results, but if you know that they are children, you can do this:

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

This will be equivalent to your second function. Currently, the first thing you have will find this:

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

The second one will not, it requires .foo be a direct child of whatever and .bar be a direct descendant of .find(".foo .bar") > allows them to be any level in depth while the .bar the .foo descendant.

+6
source

As an alternative:

 $('whatever .foo .bar') 

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

As long as whatever is the standard CSS3 selector (not using any extensions of Sizzle-specific extensions), a single document-related selector will be passed to document.querySelectorAll in modern browsers, which will be much faster than a Sizzle manual tree walk .

[Although in theory it should be possible to use element.querySelectorAll to quickly make queries of the form $(...).find(...) , jQuery will not currently use this method due to differences of opinion regarding how relative selectors are allowed between the Selectors API and the standard jQuery behavior.]

0
source

Source: https://habr.com/ru/post/1311074/


All Articles