I have a table with 10 rows and data is
ABC XYZ 30% (ABC)
ABC MNO 91% (XYZ)
var table = document.getElementById("table2");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
var data = col.innerText;
var data1 = data.split(" ");
if(data1[0] == "91%"){
row.cells[j].css( "color", "red" );
}
}
}
I want to add red color to the cells which are above 90%. How to do it. I know in back-end we can do it but now I am using only html and CSS.
Slight variation in your code can make it works
var table = document.getElementById("table2"); for (var i = 0, row; row = table.rows[i]; i++) { for (var j = 0, col; col = row.cells[j]; j++) { var data = col.innerText; // replace % symbol, parse and compare with number if (+data.replace('%', '') > 90) { // update style property of cell col.style.color = "red"; } } }
<table id="table2"> <tr> <td>ABC</td> <td>XYZ</td> <td>30%</td> <td>(ABC)</td> </tr> <tr> <td>ABC</td> <td>MNO</td> <td>91%</td> <td>(XYZ)</td> </tr> </table>
If a single column contains the entire string then do something like this
var table = document.getElementById("table2"); for (var i = 0, row; row = table.rows[i]; i++) { for (var j = 0, col; col = row.cells[j]; j++) { // get the percentage value from string var data = col.innerText.match(/(\\d+(?:\\.\\d+)?)%/); // check match found or not then parse and compare with number if (data && +data[1] > 90) { // update style property of cell col.style.color = "red"; } } }
<table id="table2"> <tr> <td>ABC XYZ 30% (ABC)</td> </tr> <tr> <td>ABC MNO 91% (XYZ)</td> </tr> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.