jQuery difference between find() and children() wh

2019-06-27 17:10发布

问题:

In the process of answering the following jQuery question Need help in Optimizing the below jquery code , I stumbled across another question about .find() and .children().

The question was, given four selectboxes with ids state, city, branch, branchAddress, to remove all but the first option for each select boxes.

There has been several answers posted. Among those were :

  1. $('#state,#city,#branch,#branchAddress').children('option:not(:first)').remove();
  2. $('#state,#city,#branch,#branchAddress').children('option:not(:first-child)').remove();
  3. $('#state,#city,#branch,#branchAddress').find('option:not(:first)').remove();

Solution 1 does not seem to work (removing all options, except the first option of the first select box) according to this js fiddle ( http://jsfiddle.net/QkNRf/1/ )

Solution 2 and 3 seem to work perfectly.

I would be glad if someone could point me what I missed, or explain to me why solution 3 works where solution 1 does not.

回答1:

All the other answers are correct but I think the important part in the doc that explains why example 1 fails and why number 3 works is that while .children() effectively filters the results from the previous selector, .find() will perform selector-context search, so (I assume) it will perform the 'option:not(:first)' search in all 4 contexts and collate the results, while .children() will first collate the results and then filter using 'option:not(:first)' effectively removing all but the very first...

The depth of search is irrelevant in this case.



回答2:

From the docs: .children():

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.