How do I iterate through table rows and cells in JavaScript?

前端 未结 9 1012
旧时难觅i
旧时难觅i 2020-11-22 13:05

If I have an HTML table...say

<
9条回答
  •  -上瘾入骨i
    2020-11-22 13:28

    You can use .querySelectorAll() to select all td elements, then loop over these with .forEach(). Their values can be retrieved with .innerHTML:

    const cells = document.querySelectorAll('td');
    cells.forEach(function(cell) {
      console.log(cell.innerHTML);
    })
col1 Val1
col1 Val1 col2 Val2
col1 Val3 col2 Val4

If you want to only select columns from a specific row, you can make use of the pseudo-class :nth-child() to select a specific tr, optionally in conjunction with the child combinator (>) (which can be useful if you have a table within a table):

const cells = document.querySelectorAll('tr:nth-child(2) > td');
cells.forEach(function(cell) {
  console.log(cell.innerHTML);
})
col1 Val1 col2 Val2
col1 Val3 col2 Val4

提交回复
热议问题