Both :checked and :selected seem to provide equal results when working with <option> elements. Is there any advantage to using one over the other? If :selected does the same thing as :checked, what is the reason for it to be included in jQuery at all?
Example:
<p class="p1">Select a value</p>
<p class="p2">Select a value</p>
<select>
<option value="a">Option one</option>
<option value="b">Option two</option>
</select>
$('select').on('change', function(){
$('.p1').text(function() {
return $('option:selected').text();
});
$('.p2').text(function() {
return $('option:checked').text();
});
});
JS Bin demo
Judging by the documentation, it seems that :selected is identical to :checked with the exception that it only matches option elements. This is corroborated by HTMLOptionElement being the only element type in the DOM to have a selected property (which is what :selected uses to test the selectedness of an element). In other words, when you're only interested in option elements, both selectors are identical — except :selected is non-standard.
Since the documentation itself recommends using standard selectors to maximize performance (and because why would you not use a standard selector over a non-standard one if given the choice?), I don't think there is any reason to use :selected in any situation ever. I can't think of any situation in which *:selected would be preferable to option:checked (seriously, when was the last time you used a pseudo-class of this kind without a type selector?).
Perhaps the reason it was included in jQuery was because Selectors 3 (in which :checked appears) wasn't yet standardized at the time jQuery was born, but :checked has been in the spec since 2000, so I'm not entirely convinced that's really the reason.
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