首页 > 解决方案 > Console throwing error with style property

问题描述

I can't figure out why I'm getting this error. Everything is working as expected only that the console is throwing this error. Can anyone determine why?

Unable to get property 'style' of undefined or null reference

function openEditTable(tableid, DDid, ADid, Editid, UCid){
    var table = document.getElementById(tableid);
    var DDid = document.getElementById(DDid);
    var ADid = document.getElementById(ADid);
    var Editid = document.getElementById(Editid);
    var UCid = document.getElementById(UCid);

    for (var i = 0, row; row = table.rows[i]; i++) {
        col = row.cells[8];
        col.style.display = '';
        DDid.style.display = 'none';
        ADid.style.display = 'none';
        Editid.style.display = 'none';
        UCid.style.display = '';
    }
}

标签: javascript

解决方案


To achieve expected result, use below option of finding position of column and using same index for styling the cell

Sample working code for reference

function openEditTable(tableid, colName){
    var table = document.getElementById(tableid);
      let index;
    for (var i = 0, row; row = table.rows[i]; i++) {

       for (var j = 0; j<row.cells.length; j++) {
          if(row.cells[j].textContent ===colName){
             index = j
          }
         if(row.cells && row.cells[index]){
              row.cells[index].style.color = 'red';      
         }

    } 
   } 
}

openEditTable('tableid', 'Lastname')
table tr td{
  border: 1px solid black
}
<table style="width:100%" id="tableid">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

codepen - https://codepen.io/nagasai/pen/gOOaXvr


推荐阅读