我知道有一种访问顺序元素的方法,但我不确定如何通过索引访问它们。有办法吗?
我正在寻找类似的东西:
document.getElementById('table1').cell[1]
答案 0 :(得分:17)
要通过行中的行索引和单元格索引访问单元格,您可以使用:
var rowIndex = 0;
var cellIndex = 1;
document.getElementById('table1').rows[rowIndex].cells[cellIndex];
这将访问第一行(索引0)
中的第二个单元格(索引1)如果您只想使用单元格索引(而不是跟踪行)并让它遍历每行中的单元格,则可以执行此操作,但前提是每行都具有相同数量的单元格。以下代码将访问表中的第四个单元格(索引3),无论它是在行0,1或3中;只要每行具有相同数量的单元格:
var cellIndex = 3;
var table = document.getElementById('table1');
var num_columns = table.rows[0].cells.length;
var cell = table.rows[Math.floor(cellIndex/num_columns)].cells[cellIndex % num_columns];
答案 1 :(得分:4)
表.rows
collection提供对行的访问权限。行.cells
集合提供对该行的单元格的访问。两者都使用从零开始的索引并具有.length
属性。所以:
var table = document.getElementById('table1');
alert(table.rows.length); // number of rows
alert(table.rows[2].cells.length); // number of cells in row 3
alert(table.rows[2].cells[5].innerHTML); // contents of 6th cell in 3rd row
答案 2 :(得分:2)
要按ID将查询限制为元素树,可以使用querySelector
:
document.getElementById('table1').querySelector('#cell1');
但是当你可以简单地做
时,这只是多余的document.getElementById('cell1');
编辑:为了更好地回答OP的请求,可以通过这种方式顺序访问表格的单元格:
document.getElementById('table1').tBodies[i].rows[j].cells[k];
这将选择表k
的第j
个i
行的<tbody>
个单元格。
如果您的表格只有一个<tbody>
元素(与通常一样),或者您想要从.tBodies[i]
独立访问这些单元格,则可以省略{{1}}部分。
答案 3 :(得分:2)
document.querySelector('table td'); //Done. IE8 and above supported.
//Only the first one will be selected.
document.querySelector('#table1 td'); //First cell in #table1
document.querySelector('#table1 td:nth-child(3)'); //Third cell in #table1
document.querySelectorAll('#table1 td')[2]; //or this
答案 4 :(得分:0)
为<td>
单元格指定一个ID:
<td id="mycell">
然后,您可以使用getElementById()
:
document.getElementById('mycell');