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)?
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";
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With