【问题标题】:How to access specific tr and td from a tbody without jQuery?如何在没有 jQuery 的情况下从 tbody 访问特定的 tr 和 td?
【发布时间】:2021-08-10 17:23:41
【问题描述】:

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

tbody

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

【问题讨论】:

    标签: javascript html html-table


    【解决方案1】:

    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>

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    相关资源
    最近更新 更多