When looping over a group of items using jquery selectors is there a way to find out how many items there are on the collection?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you’re using chained syntax:
…I don’t think there’s any (reasonable) way for the code within the
eachfunction to know how many items there are. (Unreasonable ways would involve repeating the selector and usingindex.)But it’s easy enough to make the collection available to the function that you’re calling in
each. Here’s one way to do that:As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array’s
forEach. The arguments that get passed toforEach‘s callback are the entry being visited (what jQuery gives you asthisand as the second argument), the index of that entry, and the array you called it on:That assumes an at least vaguely modern JavaScript engine and/or a shim for
Array#forEach.Or for that matter, give yourself a new tool:
Usage: