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 :
$('#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 (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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With