根据单元格内容更改样式元素
问题描述:
我有一张桌子,像这样:
I have a table, like so:
<table>
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>three</td>
<td>one</td>
</tr>
</table>
使用Javascript,如何基于单元格的内容搜索表格并更改样式元素(例如backgroundColor
)(例如,将所有带有单词"one"的单元格的背景颜色设为红色)?
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)?
答
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";
}