Reputation: 97
function foo() {
$('#bar > table > tbody > tr').each(function () {
$(this).find('td:nth-child(3)').text() == '1' && $(this).find('td:nth-child(1)').css('background-color', 'green');
$(this).find('td:nth-child(3)').text() == '2' && $(this).find('td:nth-child(1)').css('background-color', 'yellow');
$(this).find('td:nth-child(3)').text() == '3' && $(this).find('td:nth-child(1)').css('background-color', 'red');
});
}
Upvotes: 1
Views: 45
Reputation: 370689
Use an object indexed by text to find, whose values are the colors to set:
const colorsByText = {
1: 'green',
2: 'yellow',
3: 'red'
};
function foo() {
$('#bar > table > tbody > tr').each(function () {
const text = $(this).find('td:nth-child(3)').text();
const color = colorsByText[text];
if (color) {
$(this).find('td:nth-child(1)').css('background-color', color);
}
});
}
If the text will always be one of those 3 properties, you can remove the if
check - or, even better, use an array instead of an object:
const colors = ['green', 'yellow', 'red'];
function foo() {
$('#bar > table > tbody > tr').each(function () {
const text = $(this).find('td:nth-child(3)').text();
const color = colors[text - 1];
$(this).find('td:nth-child(1)').css('background-color', color);
});
}
Upvotes: 1