Following on from a previous question.
Lets say I have two checkboxes on a page loaded with jQuery 1.5.2
<input id="test1" type="checkbox"/>
<input id="test2" type="checkbox"/>
Then lets click both of them to give each the checked property.
Now lets grab all checkboxes and filter out the ones that aren’t checked
var numOfCheckedBoxes = $("input:checkbox").filter("*[checked]").size();
Now based on the answer to the previous question, I would expect numOfCheckedBoxes to equal 0 but it equals 2. I now I should just use $("input:checkbox:checked") or $("input:checkbox").filter(":checked").
This differs from if I do
var numOfCheckedBoxes = $("#test1").filter("*[checked]").size();
which sets numOfCheckedBoxes equal to 0.
Here is a jsFiddle of the first scenario in question.
Here is a jsFiddle of the second scenario in question.
Because in modern browsers, the DOM selection will be done with
querySelectorAll.This means that when doing DOM selection,
*[checked]will actually look for that specific attribute.When you do
':checked'in DOM selection, you’re using aSizzleextension that is invalid CSS, soquerySelectorAllis not used, and thereforSizzleis used, and it looks at the property as well as the attribute.So the difference here is that
.filter()doesn’t/can’t usequerySelectorAll, which means that you’re going to get the proprietary behavior given bySizzleinstead of the valid DOM behavior.It would be great if
Sizzlewas actually a compatibility patch forquerySelectorAll, but it isn’t, so you have to deal with the resulting inconsistencies.EDIT:
It appears as though there’s an optimization where if
filter()is called against multiple elements,Sizzleis used, but if only one element, thenis()is used.This matters because
is()will usematchesSelectorin browsers that have it, andmatchesSelectorwill give the same evaluation asquerySelectorAll. That evaluation differs fromSizzle.