使用getAttribute更改单元格的背景颜色

时间:2021-10-02 20:01:18

I'm attempting to loop through the cells of a table using getAttribute for a cell with a blue background, then changing it to a yellow background. I know CSS can easily accomplish this task, however I want to understand using JavaScript.

我正在尝试使用getAttribute为具有蓝色背景的单元格循环遍历表格的单元格,然后将其更改为黄色背景。我知道CSS可以很容易地完成这个任务,但是我想用JavaScript来理解。

Here is my code:

这是我的代码:

<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";
  }
}

Console log isn't returning any errors. Any thoughts guys?

控制台日志不会返回任何错误。有什么想法吗?

Thank you!

1 个解决方案

#1


2  

Note that background property isn't a DOM attribute, it's a style attribute.

请注意,background属性不是DOM属性,它是样式属性。

Note: If you refer to the specified td element, use cells[i] instead, because this keyword in this particular case will not refer to the actually iterated element, but to the window object.

注意:如果引用指定的td元素,请改用cell [i],因为在这种特殊情况下,此关键字不会引用实际迭代的元素,而是引用窗口对象。

var cells = document.getElementsByTagName('td');

for (i = 0; i < cells.length; i++) {
  if (cells[i].style.background == 'blue') {
    cells[i].style.background = "yellow";
  }
}
<table>
  <tr>
    <td>
      Cell 1
    </td>
    <td>
      Cell 2
    </td>
  </tr>
  <tr>
    <td>
      Cell 3
    </td>
    <td style="background:blue">
      Cell 4
    </td>
  </tr>
</table>

In case that you would like to refer to the DOM attribute, you could apply following code:

如果您想引用DOM属性,可以应用以下代码:

if (cells[i].getAttribute('style') == 'background:blue') {
   cells[i].style.background = "yellow";
}

#1


2  

Note that background property isn't a DOM attribute, it's a style attribute.

请注意,background属性不是DOM属性,它是样式属性。

Note: If you refer to the specified td element, use cells[i] instead, because this keyword in this particular case will not refer to the actually iterated element, but to the window object.

注意:如果引用指定的td元素,请改用cell [i],因为在这种特殊情况下,此关键字不会引用实际迭代的元素,而是引用窗口对象。

var cells = document.getElementsByTagName('td');

for (i = 0; i < cells.length; i++) {
  if (cells[i].style.background == 'blue') {
    cells[i].style.background = "yellow";
  }
}
<table>
  <tr>
    <td>
      Cell 1
    </td>
    <td>
      Cell 2
    </td>
  </tr>
  <tr>
    <td>
      Cell 3
    </td>
    <td style="background:blue">
      Cell 4
    </td>
  </tr>
</table>

In case that you would like to refer to the DOM attribute, you could apply following code:

如果您想引用DOM属性,可以应用以下代码:

if (cells[i].getAttribute('style') == 'background:blue') {
   cells[i].style.background = "yellow";
}