如何从没有jQuery的主体访问特定的tr和td ?



我试图访问第一个tr,并从中访问第二个和第三个td元素。但是,我希望在不使用jQuery或任何其他库的情况下实现这一点。我已经尝试通过使用.childNodes[1]或试图将其视为数组来访问它。我想知道如何在一般情况下做到这一点,以便我可以将其应用于其他表(如果我想访问不同的tr)

tbody:

<tbody>
<tr role="row" class="odd">
<td>0</td>
<td>15</td>
<td>200</td>
</tr>
</tbody>

HTMLTableElement元素包含一个rows属性,HtmlTableRowElement元素有一个cells属性。都是集合

或者,您可以使用document.querySelectorAll检索(数组)第一行中的单元格,然后检索其中的最后两个。

您也可以使用一个css查询(最后一个选项)获得目标单元格。

const firstRow = document.querySelector(`table tbody`).rows[0];
console.log(firstRow);
const secondTdOfFirstRow = firstRow.cells[1];
console.log(secondTdOfFirstRow);
// alternative
const firstRowLastTwoCells = [...document
.querySelectorAll(`table tbody tr:nth-child(1) td`)].slice(-2);
console.log(firstRowLastTwoCells);
// another alternative
const firstRowLastTwoCellsInOneGo = document
.querySelectorAll(`table tbody tr:nth-child(1) td:not(:first-child)`);
console.log([...firstRowLastTwoCellsInOneGo])
<table>
<tbody>
<tr role="row" class="odd">
<td>0</td>
<td>15</td>
<td>200</td>
</tr>
</tbody>
</table>

最新更新