I am having trouble figuring out why .length always seems to return 1 when counting elements having the same id in the page. I do know that there should only be elements with unique html id's in an html document, but in the project I am working on, the user may inadvertently add duplicates.
So, is it the normal behaviour for jQuery to always return 1 when counting elements id's?
<div id="1">foo</div>
<div id="1">foo</div>
jQuery(function(){
alert(jQuery('#1').length); // returns 1
});
I have built an example here: http://jsfiddle.net/eSNZx/
Thanks for your help
Returns 0 or 1. Multiple elements with the same id is not valid.
It's not a jQuery or javascript restriction but HTML one. Check 7.5.2 Element identifiers: the id and class attributes for official word about that.
Yes, this is normal. However, you can work around it by using the attribute equals selector.
$("[id=1]").length
Obviously, having non-unique id's is invalid. Since you are dealing with user input, it is possible to occur if you aren't preventing it.
Alternatively, you can use .children(), .find(), .siblings(), and/or .filter() to get the same effect. Or possibly even a more complex selector, such as #parent #1
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