I have an html table and in a particular column the text is either set to 'Y' or 'N'. I'm wondering if it is possible to set the colour of the text to Red programmatically on load if the value is'N'?
<table>
<tr>
<td>N</td>
<td>Y</td>
</tr>
</table>
Using jQuery, it's easy:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#table_id td.y_n').each(function(){
if ($(this).text() == 'N') {
$(this).css('background-color','#f00');
}
});
});
</script>
</head>
<body>
<table id="table_id">
<tr><th>Question</th><th>Y/N?</th></tr>
<tr><td>I am me.</td><td class="y_n">Y</td></tr>
<tr><td>I am him.</td><td class="y_n">N</td></tr>
<tr><td>I am not sure.</td><td class="y_n">Y</td></tr>
<tr><td>This is a table.</td><td class="y_n">Y</td></tr>
</table>
</body>
</html>
Note: I tested the above file and it works. Copy to your desktop, save as yn.html, and run in a browser.
EDIT: To accomplish with a pure selector and not rely on the if statement...
$(document).ready(function(){
$("#table_id td.y_n:contains('N')").css('background-color','#fcc');
});
This was following Tyler Holien's answer. This would be the better way to do it, since it doesn't involve so many function calls and is more expressive in less code. NOTE: Unfortunately, do not use this version if there would be other content that may contain N's and should not be selected, since contains will select all text that has N in it, not JUST the 'N'-only text.
Try the following CSS:
td[value="N"] {
color: red;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With