Home > Mobile >  How to iterate through this html table and get data from rows whose last col is not empty?
How to iterate through this html table and get data from rows whose last col is not empty?

Time:05-17

I've been trying to get this data, but the array comes out empty:

function saveData() {
  var tableData = [];
  var table = document.getElementById("dtable");
  console.log(table)

  for (var i = 0; i < table.length; i  ) {
    let tableCells = table.rows.item(i).cells;
    let cellLength = tableCells.length;

    for (let j = 0; j < cellLength; j  ) {
      let cellVal = tableCells.item(j).innerHTML;
      tableData.push(cellVal)
    }
  }
  console.log(tableData)
  rows = JSON.stringify(tableData);
  google.script.run.formToSheets(rows);
}

Thanks for any help! enter image description here

CodePudding user response:

In your script, as one of several possible modifications, how about the following modification?

From:

var tableData = [];
var table = document.getElementById("dtable");
console.log(table)

for (var i = 0; i < table.length; i  ) {
  let tableCells = table.rows.item(i).cells;
  let cellLength = tableCells.length;

  for (let j = 0; j < cellLength; j  ) {
    let cellVal = tableCells.item(j).innerHTML;
    tableData.push(cellVal)
  }
}
console.log(tableData)

To:

var table = document.getElementById("dtable");
console.log(table)

var [, ...tr] = table.querySelectorAll("tr");
var tableData = [...tr].map(r => {
  var td = r.querySelectorAll("td");
  return [...td].map((c, j) => j != 3 ? c.innerHTML : c.querySelectorAll("select")[0].value);
});
console.log(tableData)
  • In this modification, from a table, the table rows are retrieved. And, the table cells are retrieved from the table rows. In teh case of the dropdown list, the value is retrieved from the dropdown list.

Note:

  • When this modification was not the direct solution to your issue, I think that when you provide your whole script, it will help to correctly understand your question.
  • Related