Javascript 使用getAttribute更改单元格';背景色
我试图使用getAttribute对一个蓝色背景的单元格遍历表中的单元格,然后将其更改为黄色背景。我知道CSS可以轻松完成这项任务,但我想了解如何使用JavaScript 这是我的密码:Javascript 使用getAttribute更改单元格';背景色,javascript,dom,Javascript,Dom,我试图使用getAttribute对一个蓝色背景的单元格遍历表中的单元格,然后将其更改为黄色背景。我知道CSS可以轻松完成这项任务,但我想了解如何使用JavaScript 这是我的密码: <table> <tr> <td> Cell 1 </td> <td> Cell 2 </td> </tr> <tr> <td>
<table>
<tr>
<td>
Cell 1
</td>
<td>
Cell 2
</td>
</tr>
<tr>
<td>
Cell 3
</td>
<td style="background-color:blue">
Cell 4
</td>
</tr>
</table>
var cells = document.getElementsByTagName('td');
for(i=0; i < cells.length; i++) {
if(cells[i].getAttribute('backgroundColor') == true) {
this.style.backgroundColor = "yellow";
}
}
第1单元
第2单元
第三单元
第4单元
var cells=document.getElementsByTagName('td');
对于(i=0;i
控制台日志未返回任何错误。有什么想法吗,伙计们
谢谢大家! 请注意,
background
属性不是DOM属性,而是样式属性
注意:如果您引用指定的td
元素,请改用单元格[i]
,因为这个
关键字在这种特殊情况下将不是指实际迭代的元素,而是指窗口对象
var cells=document.getElementsByTagName('td');
对于(i=0;i
第1单元
第2单元
第三单元
第4单元
背景色不是标签的属性。所以它返回null。这就是为什么你不会得到一个错误,你不需要查询属性。您只需查看单元格当前是否有蓝色背景。将if
更改为:if(单元格[i].style.backgroundColor==“蓝色”)…
getAttribute
在这里是多余的。只需使用单元格[i].style.backgroundColor==“blue”
@ScottMarcus我知道这是毫无意义的,但我已经添加了它,以防OP真的想使用样式
属性。。。(: