Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  200] [ 7]  / answers: 1 / hits: 33298  / 10 Years ago, wed, may 14, 2014, 12:00:00

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>

More From » jquery

 Answers
11

I'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


[#71017] Tuesday, May 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
savanar

Total Points: 237
Total Questions: 105
Total Answers: 99

Location: Wales
Member since Mon, May 17, 2021
3 Years ago
;