I want to change the background color of the cell based on its text contents using jquery.
Example:
For the second row in the "Exceeds" td, I want to change the background color to green because it has Exceeds as it's text...
<table>
<tr><td>Jedi Armor1</td><td>Needs</td></tr>
<tr><td>Jedi Armor2</td><td>Exceeds</td></tr>
</table>
I want to change the background color of the cell based on its text contents using jquery.
Example:
For the second row in the "Exceeds" td, I want to change the background color to green because it has Exceeds as it's text...
<table>
<tr><td>Jedi Armor1</td><td>Needs</td></tr>
<tr><td>Jedi Armor2</td><td>Exceeds</td></tr>
</table>
Share
Improve this question
edited Jun 26, 2014 at 22:10
InCode
asked May 14, 2014 at 15:26
InCodeInCode
5033 gold badges10 silver badges25 bronze badges
2
|
4 Answers
Reset to default 7I'm assuming you want to change the color of the cell and only the cell. If you want to change the color of it based on its text, use the contains() jQuery selector :
CSS :
.greenBg {
background: green;
}
jQuery :
$("td:contains('Exceeds')").addClass('greenBg');
jsFiddle Demo
Edit :
If you want to restrict this to the second column only, this would be more suited :
$("td:nth-child(2):contains('Exceeds')").addClass('greenBg');
In case someone would want to change the color of the whole column :
$("td:nth-child(2):contains('Exceeds')").closest('table').find('td:nth-child(2)').addClass('greenBg');
jsFiddle Demo
Native JS:
var td = document.getElementsByTagName("td");
var i = 0, tds = td.length;
for (i; i < tds; i++) {
if (td[i].innerHTML == "Exceeds") {
td[i].setAttribute("style", "background:green;");
}
}
Here's a jsfiddle to show: http://jsfiddle.net/vHvLh/
Update Following Question Clarification:
Demo Fiddle
To change the background color of one cell based on the value of another, you can use e.g:
$('table tr td:nth-child(4)').each(function () {
$(this).text() == 'Exceeds' && $(this).parent().find('td:nth-child(2)').css('background-color', 'green');
});
To change the background of a specific column:
$('table tr td:nth-child(2)').css('background-color', 'red');
However you should try to maintain the seperation of styles by using CSS, in which case you can accomplish this with:
table tr td:nth-child(2){
/* styles*/
}
Or..if you specifically need dynamic control, instead of allocating the style directly in jQuery, add a class:
$('table tr td:nth-child(2)').addClass('rowBackground');
Then in your CSS:
.rowBackground{
background-color:red;
}
You can use .eq()
or :eq()
selector:
$('table tr td:eq(3)').css('background-color','green');
or use .last()
if the td
that you want to change the color is always the last td
:
$('table tr td').last().css('background-color','green')
table tr td:nth-child(2) { ... }
– ndugger Commented May 14, 2014 at 15:29