1

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 come 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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.