I have a table
where tr
s are being assigned class
with js.
I have another div
that I want to reflect it on. However, my each()
function doesn't seem to be working properly.
I have the following JS:
$("table.result tr").each(function() {
if($(this).hasClass("red")) {
$("#color").addClass("red");
//bunch of other things
} else {
$("#color").addClass("green");
//bunch of other things
}
});
And this is my markup:
<table class="result">
<tr class="red">
<th>Name</th>
<th>Result</th>
</tr>
<tr class="red">
<td>John Doe</td>
<td>Pass</td>
</tr>
<tr class="red">
<td>Johnathan Doe</td>
<td>Pass</td>
</tr>
<tr class="red">
<td>Jane Doe</td>
<td>Fail</td>
</tr>
</table>
<div id="color"></div>
What I'm trying to do is, if all the tr
s have a class
of red
, only then do I want the div
to have the class of red
too else it should be green
. But the jQuery
is only testing it on the last tr
whether it has the class
or not.
But it doesn't seem to be working. It's probably a very small mistake but I cannot figure it out. Here's a jsfiddle: https://jsfiddle.net/okvv330L/6/
As you can see, since one tr
does not have the class
red
, the div
should be green
. But it's only checking the last tr
and basing it on that.
Thanks!
I got this working by using the following code:
var $rowCount = $('.result tr').length;
var $rowFill = 0;
$(".result tr").each(function() {
if($(this).is('.red')) {
$rowFill = $rowFill + 1;
}
});
if($rowFill == $rowCount) {
$('#color').addClass('red');
} else {
$('#color').addClass('green');
}
Since the each()
was only testing the last row; I got it to match the count with the number of rows. So now, it seems to work fine.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments