Get a particular cell value from HTML table using JavaScript

前端 未结 10 1015
暖寄归人
暖寄归人 2020-12-15 06:09

I want to get each cell value from an HTML table using JavaScript when pressing submit button.

How to get HTML table cell values?

10条回答
  •  孤街浪徒
    2020-12-15 06:26

    Here is perhaps the simplest way to obtain the value of a single cell.

    document.querySelector("#table").children[0].children[r].children[c].innerText
    

    where r is the row index and c is the column index

    Therefore, to obtain all cell data and put it in a multi-dimensional array:

    var tableData = [];  
    Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))}); 
    var cell = tableData[1][2];//2nd row, 3rd column
    

    To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].

提交回复
热议问题