Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery difference between find() and children() when combined with :first

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.

like image 739
jbl Avatar asked Dec 27 '22 13:12

jbl


1 Answers

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.

like image 196
Tallmaris Avatar answered May 23 '23 02:05

Tallmaris