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).

Était-ce utile?

La 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

Autres conseils

$("#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;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top