Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery counting items with class "checked"

Tags:

jquery

css

Im struggling with this one. I have a list of items and on a part of the form when something has validated it adds class "checked" to the corresponding list item.

<ul>
<li class="title">Checklist</li>
<li class="checkType checked">Card Type</li>
<li class="checkNumber checked">Card Number</li>
<li class="checkName checked">Name on Card</li>
<li class="checkMonth checked">Expiry Month</li>
<li class="checkYear checked">Expiry Year</li>
<li class="checkCode checked">Security Code</li>
</ul>

.title{font-size:23px; font-weight:bold;}
.checked{ color:#f00;}

But I need jQuery to check that each item has the class checked EXCEPT title.

Is this doable?

Demo: http://jsfiddle.net/bQtEQ/1/

Thanks to the answers I now have the following

        var counting = $("li.checked:not(.title)").length;
    if (counting == 6){
        console.log(counting);
    }
like image 784
ngplayground Avatar asked Jun 25 '12 14:06

ngplayground


People also ask

How can I count the number of elements with same class?

To count the number of elements with a specific class: Use the querySelectorAll() method to get a collection of the matching elements. Access the length property on the collection. The length property will return the number of matching elements.

How do I count the number of elements in jQuery?

To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object.

How to get the count of checked checkboxes in JavaScript?

JavaScript Code Then querySelectorAll method will return the list of checkbox type input elements which are checked. This will be done using input[type="checkbox"]:checked CSS Selector. Then finally . length property will be used to count the number of checked checkboxes.


2 Answers

This is doable with 1 simple selector

$("li.checked:not(.title)").length

The advantage here, apart from having to code less, is that the :not() selector is factored in during search to reduce the result set. This means less time for jQuery to instantiate dom elements. This means faster execution time, especially on older browsers.

like image 111
Ben Roux Avatar answered Nov 12 '22 11:11

Ben Roux


This should give you all of the <li> elements with the class 'checked' that don't have the class title:

$('li.checked').not('.title').length

However - if you only wanted the count of the checked elements:

$('.checked').length

should suffice.

like image 35
Rion Williams Avatar answered Nov 12 '22 10:11

Rion Williams