Zerox
Zerox

Reputation: 290

How to access specific tr and td from a tbody without jQuery?

I'm trying to access the first tr and from it the second and third td element. However, I want to achieve this without the usage of jQuery or any other library. I already tried accessing it by using .childNodes[1] or by trying to treat it as an array. I want to know how to do this in general so I can apply it for other tables aswell (in case I want to access a different tr)

The tbody:

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

Upvotes: 0

Views: 1564

Answers (1)

KooiInc
KooiInc

Reputation: 122888

A HTMLTableElement element contains a rows property and a HtmlTableRowElement has a cells property. Both are collections.

Alternatively you can use document.querySelectorAll to retrieve (an array of) cells within the first row and subsequently retrieve the last two of those.

You can also get the targeted cells using one css query (last alternative).

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>

Upvotes: 2

Related Questions