JQuery difference between find () and children () combined with: first

In the process of answering the next jQuery question I need help optimizing below the jquery code , I came across another question about .find() and .children() .

The question was that for four mailboxes with identifiers, state , city , branch , branchAddress , to remove everything except the first option for each selection window.

Several responses have been posted. Among them were:

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

Solution 1 does not seem to work (deleting all parameters except the first option of the first selection window) according to this js script ( http://jsfiddle.net/QkNRf/1/ )

Solution 2 and 3 seem to work fine.

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

+4
source share
2 answers

All other answers are correct, but I think that the important part of the document, which explains why Example 1 fails and why Number 3 works, is that although .children() effectively filters the results of the previous selector, .find() will execute selector-context , so (I suppose) it will search for 'option:not(:first)' in all 4 contexts and match the results, and .children() match the results first and then filter with 'option:not(:first)' , effectively deleting everything except the very first ...

In this case, the depth of the search does not matter.

+6
source

From the documents:. children () :

The .children () method differs from .find () in that only .children () moves one level down the DOM tree, while .find () can move down several levels to select descendant elements (grandchildren , etc.).

+4
source

All Articles