Tom Tom - 2 months ago 12
jQuery Question

Jquery count occurrences of class

I have a table with rows configured as :

<tr id='user0'><td></td><td></td></tr>
<tr id='site0'><td></td><td></td></tr>
<tr id='staff0'><td></td><td></td></tr>

<tr id='user1'><td></td><td></td></tr>
<tr id='site1'><td></td><td></td></tr>
<tr id='staff1'><td></td><td></td></tr>

<tr id='user2'><td></td><td></td></tr>
<tr id='site2'><td></td><td></td></tr>
<tr id='staff2'><td></td><td></td></tr>


The rows relate to a specific staff member, and each 'block' of rows has the id number increased. Eg: user0,site0,staff0 - user1,site1,staff1 - user2,site2,staff2 etc...

Some of the row
<td>
's may have a class assigned. eg:

<tr id='user0'><td></td><td class='error'></td></tr>
<tr id='site0'><td class='error'></td><td></td></tr>
<tr id='staff0'><td></td><td class='error'></td></tr>


How do I count all occurrences of that class for the 3 rows based on the ID number. So in the above example the result would be 3

Thanks

Answer

You want like this ?

$(document).ready(function () {
    var tr0 = $("tr[id$=0] .error").length;
    var tr1 = $("tr[id$=1] .error").length;
    var tr2 = $("tr[id$=2] .error").length;
    console.log(tr0);
    console.log(tr1);
    console.log(tr2);
});
Comments