Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing style elements based on cell contents

I have a table, like so:

<table>
  <tr>
    <td>one</td>
    <td>two</td>
  </tr>
  <tr>
    <td>three</td>
    <td>one</td>
  </tr>
</table>

Using Javascript, how can I search the table and change a style element (e.g. backgroundColor) based on the contents of a cell (e.g. make the background color of all cells with the word 'one' in them red)?

like image 651
user1129274 Avatar asked Jan 04 '12 06:01

user1129274


2 Answers

DEMO

var allTableCells = document.getElementsByTagName("td");

for(var i = 0, max = allTableCells.length; i < max; i++) {
    var node = allTableCells[i];

    //get the text from the first child node - which should be a text node
    var currentText = node.childNodes[0].nodeValue; 

    //check for 'one' and assign this table cell's background color accordingly 
    if (currentText === "one")
        node.style.backgroundColor = "red";
}
like image 127
Adam Rackis Avatar answered Sep 29 '22 10:09

Adam Rackis


Here's code that searches the table and sets the background color of all cells who's contents is "one". I assume you can adapt this to check for other values:

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

with this HTML:

<table id="test">
  <tr>
    <td>one</td>
    <td>two</td>
  </tr>
  <tr>
    <td>three</td>
    <td>one</td>
  </tr>
</table>

And here's a working demo: http://jsfiddle.net/jfriend00/Uubqg/

like image 45
jfriend00 Avatar answered Sep 29 '22 11:09

jfriend00