html - Javascript to change the text color -
i have html table displays value below:
<table id="tableid"> <thead> <tr> <th>column heading 1</th> <th>column heading 2</th> <th>column heading 3</th> <th>column heading 4</th> </tr> </thead> <tbody> <tr> <td> id (43.1)</td> <td>class (-23)</td> <td>age (89.6)</td> <td>num (-5)</td> </tr> <tr> <td>id (-4)</td> <td>class (-3)</td> <td>age (0)</td> <td>num (98)</td> </tr> <tr> <td>id (10)</td> <td>class (-32)</td> <td>age (7)</td> <td>num (2)</td> </tr> task @ hand change text color on condition basis. if value negative, should displayed in red, else green. have no idea how change this, till i'm able create below javascript code, not sure how handle text color , event should use. can please provide directions.
var table = document.getelementbyid('tableid'), cells = table.getelementsbytagname('td'); (var i=0,len=cells.length; i<len; i++){ cells[i].onready = function(){ // onready .. work?? console.log(this.innerhtml); } } edit: how i'm generating html table
function generatetable($associative_array){ echo '<table width="620" id ="optimization" class="optimization_table"><thead><tr><th>'; echo implode('</th><th>', array_keys(current($associative_array))); echo '</th></tr></thead><tbody>'; foreach ($associative_array $row){ array_map('htmlentities', $row); echo '<tr valign="middle"><td>'; echo implode('</td><td>', $row); echo '</td></tr>'; } echo '</tbody></table>'; } help appreciated.
get cells, iterate on them, numbers, compare agains 0 see if negative/positive, set color, done ...
var cells = document.queryselectorall('#tableid td'); ( var i=0; i<cells.length; i++ ) { var cell = cells[i]; var html = cell.innerhtml; var changed = html.replace(/([+-]?(\d|\.)+)/, function(x) { var color = (+x) < 0 ? 'red' : 'green'; return '<span style="color: ' + color + '">' + x + '</span>'; }); cell.innerhtml = changed; }
Comments
Post a Comment