Justin Adkins Justin Adkins - 5 months ago 7
jQuery Question

Count rows in table that contain specific span

Using jQuery, how do I could the number of rows in a table that contain a span with specific text?

For example, from the below table, how would I count the number of rows that have a span that says 'User'?

<table class="table table-striped table-hover table-condensed" id="CorrectionCodesList">
<tr>
<td>
<span class="label label-primary">Print</span>
Zoning is not answered
</td>
</tr>

<tr>
<td>
<span class="label label-primary">User</span>
Vehicle Type is required
</td>
</tr>

<tr>
<td>
<span class="label label-primary">Do Not Print</span>
Business Phone Number is required
</td>
</tr>

<tr>
<td>
<span class="label label-primary">Print</span>
Business Email Address is required
</td>
</tr>
</table>

Answer

You can use a filter on the TDs to see if they contain a span with text() == "User" etc:

JSfiddle: http://jsfiddle.net/TrueBlueAussie/6JW3M/

var $rows = $('#CorrectionCodesList tr').filter(function(){
    return $(this).find('td span').text() == "User";
});
alert($rows.length);

Note: This specific logic assumes 1 span only inside the TD as find().text() will only return the text of the first match.

Littel update: I tend to use scoped jQuery selectors as they will usually result in shorter code e.g:

var $rows = $('#CorrectionCodesList tr').filter(function(){
    return $('td span',this).text() == "User";
});
alert($rows.length);