I want to loop HTML tables obtained by TypeScript with for

Asked 1 years ago, Updated 1 years ago, 54 views

Thank you for watching.
We have obtained elements from HTML with tables like the ones below in TypeScript.

<body>
  <table id="test_table">
    <tbody>
      <tr>
        <td>/td><td></td><td>
      </tr>
      <tr>
        <td>/td><td></td><td>
      </tr>
      <tr>
        <td>/td><td></td><td>
      </tr>
    </tbody>
  </table>

  <script src="./js/main.js"></script>
</body>
addEventListener('load',()=>{
  constable=<HTMLTableElement> document.getElementById('test_table');
  for (let row of table.rows) {
    for (let cell of row.cells) {
        cell.textContent='test';
    }
  }
});

However, in for(let row of table.rows),
The type 'HTMLCollectionOf<HTMLTableRowElement>' is neither array nor string.ts(2495)
The error will occur.
Image
Please let me know if there is a correct way to describe it in such a case.

  • TypeScript 3.9.6
    tconfig.json is as follows
{
  "compilerOptions": {
    "target": "ES3",
    module : "UMD",
    " strict"—true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames"—true
  }
}

If there is any missing information, I will add it.
Thank you for your cooperation.

typescript

2022-09-30 18:10

1 Answers

rows and cells are ArrayLike, but they are not Iterable, so you can use for if you array them in Array.form.

constable=<HTMLTableElement> document.getElementById('test_table');
for(letrow of Array.from(table.rows)){
    for(let cell of Array.from(row.cells)){
        cell.textContent='test';
    }
}


2022-09-30 18:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.