如何解决此问题:未捕获的TypeError:无法读取null的属性'getElementsByTagName'

时间:2018-08-28 08:53:58

标签: javascript

我收到此错误未捕获的TypeError:无法从此行读取属性'getElementsByTagName'为空

var rows = document.getElementById('trans_separate').getElementsByTagName('tbody')[0].getElementsByTagName('tr');

我曾尝试将脚本从头移到正文,但是它仍然给我同样的错误。我也曾在JS fiddle中尝试过,但这似乎很好并且可行。

有人可以给我建议吗?

<body>
<script> 
var rows = 
document.getElementById('trans_separate').getElementsByTagName('tbody') 
[0].getElementsByTagName('tr');


for (i = 0; i < rows.length; i++) 
    {cells = rows[i].getElementsByTagName('td');
        if (cells[0].innerHTML == 'LTC')
            rows[i].className = "LTC";

        if (cells[0].innerHTML == 'B')
            rows[i].className = "B";   

        if (cells[0].innerHTML == 'A')
            rows[i].className = "A"; 

        if (cells[0].innerHTML == 'OTHERS')
           rows[i].className = "OTHERS"; 
    }
 </script>
 <table id='trans_separate'>
<thead>
  <tr>
    <td style="background-color: #2E86C1">
      A
    </td>
  </tr>
  <tr>
    <td style="background-color: #E67E22">
      LTC
    </td>
  </tr>
  <tr>
    <td style="background-color: #17A589">
      B
    </td>
  </tr>
   <tr>
    <td style="background-color: #F7DC6F">
      Others
    </td>
  </tr>
<thead>
<tbody>
    <tr>
        <td STYLE=display:NONE>A</td>
        <td>9.99</td>
    </tr>
    <tr>
        <td  STYLE=display:NONE>LTC</td>
        <td>5555</td>
    </tr>
    <tr>
        <td  STYLE=display:NONE>B</td>
        <td>5.223</td>
    </tr>
    <tr>
        <td  STYLE=display:NONE>OTHERS</td>
        <td>909.5</td>
    </tr>        
</tbody>
</table> 
</body>

0 个答案:

没有答案