admin管理员组

文章数量:1384149

I'm parsing an existing HTML table on a webpage into an array of numbers to later pass to a plot object. I'm learning JavaScript and it is not clear how I am supposed to iterate over the data values in HTML tags. This is what I've e 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'm bothered by the .innerText part. Is that the universal mechanism for iterating over the text elements in the <td> tags?

I'm parsing an existing HTML table on a webpage into an array of numbers to later pass to a plot object. I'm learning JavaScript and it is not clear how I am supposed to iterate over the data values in HTML tags. This is what I've e 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'm bothered by the .innerText part. Is that the universal mechanism for iterating over the text elements in the <td> tags?

Share Improve this question asked Nov 11, 2010 at 2:41 RichRich 12.7k11 gold badges68 silver badges98 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Unfortunately .innerText is not universal, most notably it's missing from Firefox. Use either .innerHTML here if it's just text in the cell or Number(cell.innerText || cell.textContent) to account for all browsers.

Yeah, what you are doing is fine, although innerText is not universally supported. Though I've got a few suggestions...

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();
}

This assumes your cell has just a number in it (or the first portion is the useful number).

  • Use var otherwise your variables are global.
  • Cache the lengths - otherwise they are calculated per iteration.
  • i++ is generally used to increment a number.

本文标签: JavaScript to parse HTML table of numbers into an arrayStack Overflow