$("#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).

有帮助吗?

解决方案

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

其他提示

$("#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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top