简体   繁体   中英

Modify the text of table cells using js

I have a table in html and I want to alter the text inside different cells using js. My table looks like this:

    <tr><td colspan="7" style="text-align:center;">Calendar evenimente tds</td></tr>
    <tr>
      <th>Data1</th>
      <th>Data2</th>
      <th>Data3</th>
      <th>Data4</th>
      <th>Data5</th>
      <th>Data6</th>
      <th>Data7</th>
    </tr>
    <tr>
      <td id="col1row1">null</td>
      <td id="col2row1">null</td>
      <td id="col3row1">null</td>
      <td id="col4row1">null</td>
      <td id="col5row1">null</td>
      <td id="col6row1">null</td>
      <td id="col7row1">null</td>
    </tr>
</table>

and my js script looks like this:

var j=0;
for(j=0;j<=7;j++)
document.getElementById("col"+j+"row1").innerHTML=j;

but I get this error:

Uncaught TypeError: Cannot set property 'innerHTML' of null

My question is whats the propper way of modifying the text inside a HTML table cell and what am I doing wrong?

The first iteration of your loop fails because there is no col0 . Rather than iterate over IDs like this, you can simply loop over the elements by tag:

Array.from(document.getElementsByTagName('td')).forEach((td, index) => {
  td.innerHTML = index
})

If you want the count to start at 1, use td.innerHTML = index + 1 instead.

loop are calling an ID that does not exist.make for loop starts with 1 instead of zero as there is no col0row1 in your html

 var j;
for(j=1;j<=7;j++){
document.getElementById("col"+j+"row1").innerHTML=j;
}

As at j = 0 there is no element with id "col0row1" hence the uncaught error.

 var j = 1 for(j=1;j<=7;j++){ document.getElementById("col" + j + "row1").innerHTML = j; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM