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?
2 Answers
Reset to default 5Unfortunately .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
版权声明:本文标题:JavaScript to parse HTML table of numbers into an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744533982a2611203.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论