You are declaring the variable twice: once in the function and once more inside the if
condition. Both of those definitions reset the variable to zero upon each iteration of the function.
Consider declaring number
once, outside the function's scope. That way, it can be incremented each time the function is called.
function checkIfAnyExist() {
if ($(this).length) {
number++;
}
console.log(number);
}
var number = 0;
$("#myTable tr:not(.discarded,.old) td:nth-child(1)").each(checkIfAnyExist);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table id="myTable">
<tr><td></td></tr>
<tr><td></td></tr>
<tr><td></td></tr>
<tr><td></td></tr>
<tr class="discarded"><td></td></tr>
<tr class="old"><td></td></tr>
</table>
You are then counting the number of "first cell"s in rows that are not .discarded
or .old
.
As @TylerRoper wisely explained, $(this).length
will never be false in this situation; every row passed to the function has a length. So the function does not appear to be useful.
jQuery's .length
by itself is a more effective method of counting the appropriate rows:
var rowCount = $("#myTable tr:not(.discarded,.old)").length;
console.log(rowCount ? rowCount + ' rows found.' : 'There are no rows.');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table id="myTable">
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr class="discarded"></tr>
<tr class="old"></tr>
</table>
Note: It might be a different story if you're trying to determine how many rows are not empty, or contain more than one cell, or contain at least one cell with content, or some other more complicated selection.