Why doesn’t this work when a select has optgroups in it?
doesn’t work
$("option:first-child").attr("selected", "selected");
works
$("select>option:first-child").attr("selected", "selected");
When I do $("select:eq(1) option:first-child").val() it appears to be getting the right option, but when I call attr() it isn’t picking the right one.
Example: http://jsfiddle.net/7J2Yb/
If you check the value of
$("option:first-child").lengthyou will notice that it is5.:first-childis selecting options that are the first child of their parent, which are:Furthermore
$("select:eq(1) option:first-child").lengthis equal to4for the same reason above. Calling.val()on the array outputs the first elements value, but the selector is selecting all 4 of them.If you want to select the first element in each
selectwrite:working example: http://jsfiddle.net/hunter/7J2Yb/2/