Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery('#id').length always return 1?

Tags:

jquery

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

like image 502
Vincent Avatar asked Nov 27 '22 17:11

Vincent


2 Answers

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.

like image 70
Claudio Redi Avatar answered Dec 11 '22 01:12

Claudio Redi


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

like image 25
Kevin B Avatar answered Dec 11 '22 00:12

Kevin B