What I'm trying to do is to count all of the elements in the current page with the same class and then I'm going to use it to be added onto a name for an input form. Basically I'm allowing users to click on a <span>
and then by doing so add another one for more of the same type of items. But I can't think of a way to count all of these simply with jQuery/JavaScript.
I was going to then name the item as something like name="whatever(total+1)"
, if anyone has a simple way to do this I'd be extremely grateful as JavaScript isn't exactly my native tongue.
To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object. where selector is the object whose length is to be calculated.
Should just be something like:
// Gets the number of elements with class yourClass var numItems = $('.yourclass').length
As a side-note, it is often beneficial to check the length property before chaining a lot of functions calls on a jQuery object, to ensure that we actually have some work to perform. See below:
var $items = $('.myclass'); // Ensure we have at least one element in $items before setting up animations // and other resource intensive tasks. if($items.length) { $items.animate(/* */) // It might also be appropriate to check that we have 2 or more // elements returned by the filter-call before animating this subset of // items. .filter(':odd') .animate(/* */) .end() .promise() .then(function () { $items.addClass('all-done'); }); }
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