oceansmoving oceansmoving - 7 months ago 10
Javascript Question

How to add class to tr only when ALL td's has a certain class?

I've been trying to create a buzzword bingo mainly using PHP. I add a specific class to the keywords from an array of 25 words that are found on a certain website. Now I just want to use jquery to style the row when all cells has that class but I can't figure out how, this is all I've got at the moment.

$('td.check').parent('tr').addClass('bingo');


PHP:

function bingo() {

$buzzwords = array(
"kaos",
"mega",
"super",
"kris",
"tragedi",
"döds",
"succé",
"avslöjar",
"chocken",
"terror",
"attack",
"mardröm",
"rekord",
"galen",
"knark",
"attentat",
"extrem",
"kollaps",
"kränkt",
"skräll",
"myten",
"problem",
"varning",
"extra",
"besked"
);

shuffle($buzzwords);

$inAb = array();


$bingocard = "<table class='tabell'>";
$bingocard .= "<thead><tr>";
$bingocard .= "<th>B</th>
<th>I</th><th>N</th>
<th>G</th><th>O</th>";
$bingocard .= "</tr></thead>";
$bingocard .= "<tbody>";
$bingocard .= "<tr>";

for($cell=0; $cell<25; $cell++)
{

$rowend = ($cell + 1) % 5;
$homepage = file_get_contents('http://www.example.com/');
$value = $buzzwords[$cell];
$antal = substr_count($homepage, $buzzwords[$cell]);
if ($antal > 0) {
$bingocard .= "<td class='check' style='color: red;'>"
. $buzzwords[$cell] . "</td>";
array_push($inAb,$buzzwords[$cell]);
}
else {
$bingocard .= "<td>"
. $buzzwords[$cell] . "</td>";
}

if($rowend == 0 && $cell < 24) {
$bingocard .= "</tr><tr>";
}
}

$bingocard .= "</tr>";
$bingocard .= "</tbody>";
$bingocard .= "</table>";
echo $bingocard;
}

bingo();

Answer

Check that number of tds which are children of tr is the same as number of tds with class check which are children of the same tr:

if ( $("tr").find("td").length == $("tr").find("td.check").length ) {
    $("tr").addClass( "check" );
}

Furthermore, use each to test every tr of your table .tabell:

$( ".tabell" ).find( "tr" ).each(function(idx) {
    var tr$ = $( this );
    if ( tr$.find("td").length == tr$.find("td.check").length ) {
        tr$.addClass( "check" );
    }
});

Update: Because tr with th has no td (0) and no td.check (0 too), you should skip somehow first row. Maybe something like

$( ".tabell tbody" ).find( "tr" )` 

or

0 < $("tr").find("td").length && $("tr").find("td").length == $("tr").find("td.check").length