in jQuery, how to get the quantity of an element based on id?

I have a bunch of elements with <div id='id1'></div> and would like to return the quantity/count of them.

I am using the following code, but it always returns the value of 1:

alert( $('#id1').size() );

What am I doing wrong?


Note that there should only be one item with a particular identifier to begin with; what you're doing is considered invalid. jQuery rightfully stops after returning the first one it finds.

If you used class="foo" instead, you could use .size() correctly. For example, on this question's StackOverflow page:

>>> $('.votecell').size()

If you want to have multiple divs with the same 'something' you need to use a class.

<div class='class1'></div>

alert( $('div.class1').size() );

There should be only 1 item with any given id - if you need to tag multiple divs, you should use class. I suspect jQuery optimises for $('#id') and returns only the first, hence size always returns 1

While the ID should be unique, $("[id='id1']").length will get you what you want (In case you cannot change the HTML).

I figured out my own answer. I should have done:

alert( $('body #id1').length );

I just needed it to return a value greater than 1, and this does the trick.

I know I should be using class instead of id, but in my program, class is already used for something specific and I do another action based on the class which can't have multiple class names, but that's another story, and outside the scope of this topic. Thanks to everyone who chimed in though.

Need Your Help

Set registry to control working dir when associating file-type with application

installer registry inno-setup file-association

I'm using Inno for an installer, and I want to associate a file type with my app: