如何在没有 jQuery 的情况下从 tbody 访问特定的 tr 和 td?
How to access specific tr and td from a tbody without jQuery?
我正在尝试访问第一个 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
element contains a rows
property and a 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>
我正在尝试访问第一个 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
element contains a rows
property and a 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>