简体   繁体   中英

Change a cell colour based on cell content

I have some basic JavaScript code to scan the cells of an HTML table, and change the background colour based on an exact value, eg if the cell value is 5, then change the color to red, and this works fine :

var cells = document.getElementById("test").getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
if (cells[i].innerHTML == "5") {
    cells[i].style.backgroundColor = "red";
    }   
}

Typical table content :

Now, my table cells actually all contain [present/absent] figures, in the format of eg 2/0 (2 present, 0 absent), and 2/1 (2 present, 1 absent).

I am trying to highlight the cells where the figure after the '/' is greater than 0, in other words, highlight only the cells where there are absences.

I am struggling to find a way to actually do this, as I'm completely new to JavaScript. Any help would be appreciated!

Thank you.

You can split the innerHTML by / and check if its bigger than 0:

if (cells[i].innerHTML.split("/")[1] > 0) {
    cells[i].style.backgroundColor = "red";   
}

Not that this will throw an error if one of your cells doesn't contain a / , so you should add a check for that first.

var splitted = cells[i].innerHTML.split("/");
if (splitted.length > 1 && splitted[1] > 0) {
    // ...
}

Without seeing your HTML (at the time of writing) the best I can offer is the following:

// retrieve all the <td> elements within a <table>
// Use a more specific selector than 'table', such
// as a class-name or id if you have multiple <table>
// elements:
var tableCells = document.querySelectorAll('table td'),

    // converts the collection of <td> elements into
    // an Array, using Array.from():
    tableCellsArray = Array.from( tableCells ),

    // finds a sequence of one or more (+) number (\d)
    // characters following a slash (\/):
    reg = /\/\d+/,

    // 'empty' variable for use within the
    // (later) Array.prototype.forEach():
    number;

// iterating over each of the <td> elements in the
// array we created earlier using Array.prototype.forEach():
tableCellsArray.forEach(function(cell){
  // 'cell': a reference to the current <td> in the
  // array of <td> elements over which we're iterating.

  // here we use String.prototype.match()
  // to recover the matching number(s), if any,
  // from the text-content of the <td>:
  number = cell.textContent.match(reg);

  // if no match then number will be equal to null,
  // so we first test that there is a match and
  // if there is we convert the found number into
  // a base-10 number using parseInt() and test if
  // that found number is greater than zero:
  if (number && parseInt(number[1], 10) > 0) {

    // if both the above are true, then here we
    // use the Element.classList API to add the
    // 'hasAbsences' class to the current <td>
    // element:
    cell.classList.add('hasAbsences');
  }
});

And specify the .hasAbsences class in the CSS.

 var tableCells = document.querySelectorAll('table td'), tableCellsArray = Array.from(tableCells), reg = /\\/(\\d+)/, number; tableCellsArray.forEach(function(cell) { number = cell.textContent.match(reg); if (number && parseInt(number[1], 10) > 0) { cell.classList.add('hasAbsences'); } }); 
 table { border-collapse: collapse; } td { border: 1px solid #000; padding: 0.2em 0.5em; text-align: center; } td.hasAbsences { background-color: red; } 
 <table> <tbody> <tr> <td>1/2</td> <td>2/0</td> <td>3/0</td> <td>4/0</td> <td>5/1</td> </tr> <tr> <td>1/0</td> <td>2/0</td> <td>3/-1</td> <td>4/0</td> <td>5/0</td> </tr> <tr> <td>1/0</td> <td>2/2</td> <td>3/0</td> <td>4/6</td> <td>5/0</td> </tr> </tbody> </table> 

JS Fiddle demo .

Does it only contains numbers?

One way to do it is with parseInt the innerHTML:

 var cells = document.getElementById("test").getElementsByTagName("td"); for (var i = 0; i < cells.length; i++) { if (parseInt(cells[i].innerHTML.split('/')[1]) > 0) { cells[i].style.backgroundColor = "red"; } } 
 <table id="test"> <tr> <td> 0/0 </td> <td> 1/0 </td> <td> 2/1 </td> </tr> </table> 

EDIT: Got the question wrong edited..

Please Try this one.

var cells = document.getElementById("test").getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
if (cells[i].innerHTML.indexOf('/') > -1 && parseInt(cells[i].innerHTML.split("/")[1]) > 0) {
    cells[i].style.backgroundColor = "red";
    }   
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM