jQuery counting elements by class - what is the best way to implement this? jQuery counting elements by class - what is the best way to implement this? javascript javascript

jQuery counting elements by class - what is the best way to implement this?


Should just be something like:

// Gets the number of elements with class yourClassvar 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');    });}


Getting a count of the number of elements that refer to the same class is as simple as this

<html>    <head>        <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>        <script type="text/javascript">            $(document).ready(function() {                alert( $(".red").length );            });        </script>    </head>    <body>        <p class="red">Test</p>        <p class="red">Test</p>        <p class="red anotherclass">Test</p>        <p class="red">Test</p>        <p class="red">Test</p>        <p class="red anotherclass">Test</p>    </body></html>


var count = $('.' + myclassname).length;