Making Negative Numbers turn Red using CSS and Javascript
A common thing one wants to do in a table of financial figures is to turn negative numbers red. Given that folks would rather use CSS than <font>, there's some conflicting thinking around the right way to do it.
Some propose adding "negative" a css class like:
<TD CLASS="financial negative">-190</TD>
but others find that distasteful and say:
- number is a data type.
- currency is both a presentational instruction and a sub-type of the number data type.
- negative is neither type nor presentational — it’s dependent on the data value, not the type or the author’s formatting preference. It doesn’t belong there. [Xaprb]
and go on to provide a clever CSS-only technique that works everywhere but IE6 (demo here).
In the specific situation I've got, I'd like to make the change without changing any server-side code (which precludes adding a "negative" css class) and I need it to work everywhere (which nixes clever css).
So, here's my not-so-clever Javascript solution (Warning, I'm not a Javascript guy so give Phil a few minutes and he'll no doubt include color commentary).
<html> <head> <style type="text/css"> td.negative { color : red; } </style> <script language="JavaScript" type="text/javascript"> <!-- function MakeNegative() { TDs = document.getElementsByTagName('td'); for (var i=0; i<TDs.length; i++) { var temp = TDs[i]; if (temp.firstChild.nodeValue.indexOf('-') == 0) temp.className = "negative"; } } //--> </script> </head> <body> <table id="mytable"> <caption>Some Financial Stuff</caption> <thead> <tr><th scope="col">Date</th><th scope="col">Money is good</th></tr> </thead> <tbody> <tr><td>2006-05-01</td><td>19.95</td></tr> <tr><td>2006-05-02</td><td>-54.54</td></tr> <tr><td>2006-05-03</td><td>34.45</td></tr> <tr><td>2006-05-04</td><td>88.00</td></tr> <tr><td>2006-05-05</td><td>22.43</td></tr> </tbody> </table> <script language="JavaScript" type="text/javascript"> <!-- MakeNegative(); //--> </script> </body>
May not be Web 2.0, and it likely doesn't please the standards wonks, but it works.
UPDATE: Similar attempt seen here.
About Scott
Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.
About Newsletter


