Reputation: 48817
<select id="select1">
<option value="11">11</option>
<option value="12">12</option>
</select>
<select id="select2">
<option value="21">21</option>
<option value="22">22</option>
</select>
Behavior of the find()
and the children()
methods:
find()
:
$('#select1, #select2').find('option:not(:first)').remove();
Works as expected: select1
has only option 11
and select2
has only option 21
children()
:
$('#select1, #select2').children('option:not(:first)').remove();
Works weirdly: select1
has only option 11
but select2
has no option anymore...
Why?
Upvotes: 2
Views: 5697
Reputation: 33661
From what I see
$('#select1, #select2').find('option:not(:first)')
is equal to
$('#select1 option:not(:first), #select2 option:not(:first)')
not
$('#select1, #select2').children('option:not(:first)')
Think about the context selector as it's the same as using .find()
$('option:not(:first)',$('#select1, #select2'))
By using children with first.. you are only getting the first children option returned in collection.. whereas the context/find selector looks for the first in each context
Upvotes: 2
Reputation: 95022
I can't explain why the .find
is working with :first
, but the .children
isn't working with :first
because :first
gets the first selected element in the set of selected elements, not the ones that are the first child. What you want is :first-child
.
// children
$('#select1, #select2').children('option:not(:first-child)').remove();
// find
$('#select3, #select4').find('option:not(:first-child)').remove();
Demo: http://jsfiddle.net/tyZzy/2/
This may be a bug, though it needs more research.
Upvotes: 3