JavaScript to parse an HTML number table into an array

I am parsing an existing HTML table on a web page into an array of numbers in order to go to the plot object later. I am learning JavaScript, and it is unclear how I should iterate over data values โ€‹โ€‹in HTML tags. This is what I came up with:

for (i = 0; i < table.rows.length; i += 1) {
   row = table.rows[i];
   for (j = 0; j < row.cells.length; j += 1) {
       cell = row.cells[j];
       coord[j] = Number(cell.innerText);
   }
   data[i] = coord.slice();
}

I am concerned about the .innerText part. Is this a universal mechanism for iterating over text elements in tags <td>?

+1
source share
2 answers

Unfortunately itโ€™s .innerTextnot universal , in particular it is absent in Firefox. Use .innerHTMLhere if it's just text in a cell or Number(cell.innerText || cell.textContent)to account for all browsers.

+5
source

, , , , innerText . ...

var coords = [],
    data = [];

for (var i = 0, rowsLength = table.rows.length; i < rowsLength; i++) {
   var row = table.rows[i];
   for (var j = 0, cellsLength = row.cells.length; j < cellsLength; j++) {
       var cell = row.cells[j];
       coord[j] = Number(cell.innerHTML);
   }
   data[i] = coord.slice();
}

, ( - ).

  • var, .
  • - .
  • i++ .
+1

Source: https://habr.com/ru/post/1681956/


All Articles