I have some htmls, where some tags does not have any children, and I want to identify them and count the number of those tags.
I have tried the following and it doesn’t seem to work:
var count = 0;
$("th[class=gridlabel]").each(function(){
if($("th[class=gridlabel]").children().length<1)
{
count++;
}
});
return count;
alert(count);
not sure what’s the issue here.
I have added some additional scripts from the html source code, I want to ensure the “count” will only count the first two tags, for “answer 3” and “answer 4”, as their tags do not have children:
<tr>
<th class="gridlabel">answer 3</th>
<td headers="q12_header1" class="gridcell"><input><div><span>answer 3</span><label>1</label></div></td>
<td headers="q12_header2" class="gridcell"><input><div><label></label></div></td>
</tr>
<tr>
<th class="gridlabel">answer 4</th>
<td headers="q12_header1" class="gridcell"><input><div><span>answer 4</span><label>1</label></div></td>
<td headers="q12_header2" class="gridcell"><input><div><label></label></div></td>
</tr>
<tr>
<th class="gridlabel">other specify 1<input><label>other specify 1</label></th>
<td><input><div><span>other specify 1</span><label>1</label></div></td>
<td><input><div><label>2</label></div></td>
</tr>
Update
Given the HTML you provided, you could use something like this if you know that “non-empty” cells will have an input child :
If you want something a little more flexible, but a little longer, you can do something like :
That way you’ll cover any possible child tag. It really depends on what you need.