Question

$("#mytable td").length; 

counts the number of tds in the #mytable.

How to count among that tds only tds that have no attribute class (have no any classes).

Was it helpful?

Solution

Although plalx's answer may work, it's delicate, but it's perfectly possible to have this:

<td class=""></td>

...which would match his selector. And in fact, it's quite common, particularly if you started out with a class on the cell but then removed it with removeClass or toggleClass.

To be sure, you do this:

var countWithNoClasses = $("#mytable td").filter(function() {
    return $.trim(this.className) === "";
}).length;

Example | Source

OTHER TIPS

$("#mytable td:not([class])").length;

The above will capture elements without a class attribute and the following will capture elements without a class attribute or with class="".

$('#mytable td:not([class]), #mytable td[class=""]').length;

However you still might have issues with something like class=" " so using a filter function like already shown by T.J. Crowder would be safer.

$("#mytable td").filter(function() {
    //the replaces just trim the value
    return this.className.replace(/^\s+/, '').replace(/\s+$/, '') === "";
}).length;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top