I have a checkbox declared in my html like this:
<input id="names" name="names" type="checkbox" value="1">One</input>
<input id="names" name="names" type="checkbox" value="2">One</input>
<input id="names" name="names" type="checkbox" value="3">One</input>
I thought $('#names') will give me handle to all the checkbox elements but it doesn’t, however $('input#names') does.
$('#names').length is 1.
and
$('input#names').length is 3
Why is the difference?
jsfiddle: http://jsfiddle.net/Urbw5/8/
Thanks,
Chris.
The difference is immaterial,
idvalues must be unique within a document. If you need to group the inputs, you’ll have to use something other thanid(classis frequently [over]used for this, but you can do it structurally as well — for instance, allinputelements within a given container).The reason for the difference in the results you’re seeing lies in how jQuery’s selector engine (Sizzle) optimizes. If you pass in a simple ID-based selector, Sizzle uses
document.getElementById(and then checks that what it got back really has thatid, because of bugs in IE prior to IE8). So it returns one element.But if you pass in a compound selector like
input#names, it doesn’t follow that optimization path and actually does a DOM search (either directly in its own code, or viadocument.querySelectorAllif the browser supports it). Usually that involves searching for all matching elements first (e.g., allinputelements), and then filtering the list according to the other qualifiers. So it happens that on your test browser, either Sizzle or the browser’s selector engine isn’t short-circuiting that selector even though it should know that having found one matching element, that’s all it needs to do.