offline version v3


164 of 264 menu

cells property

The cells property stores a collection of td and th cells of a tr row. It applies to table row only.

Syntax

tr.cells;

Example

Let's iterate through all the rows of a table using the rows property, and in each row we iterate its cells using the cells property:

<table id="table"> <tr> <td>1</td><td>2</td><td>3</td> </tr> <tr> <td>4</td><td>5</td><td>6</td> </tr> <tr> <td>7</td><td>8</td><td>9</td> </tr> </table> let table = document.querySelector('#table'); for (let row of table.rows) { for (let cell of row.cells) { console.log(cell); } }

Example

Let's loop through all the rows of a table using the rows property and find out the number of cells in each row:

<table id="table"> <tr> <td>1</td><td>2</td><td>3</td><td>4</td> </tr> <tr> <td>1</td><td>2</td><td>3</td> </tr> <tr> <td>1</td><td>2</td> </tr> </table> let table = document.querySelector('#table'); for (let row of table.rows) { console.log(row.cells.length); }

Example

Let's set a background of the first cell:

<table id="table"> <tr> <td>1</td><td>2</td><td>3</td> </tr> <tr> <td>4</td><td>5</td><td>6</td> </tr> <tr> <td>7</td><td>8</td><td>9</td> </tr> </table> table, td { border: 1px solid black; } let table = document.querySelector('#table'); table.rows[0].cells[0].style.background = 'red';

:

Example

Let's set a background of diagonally table cells:

<table id="table"> <tr> <td>1</td><td>2</td><td>3</td> </tr> <tr> <td>4</td><td>5</td><td>6</td> </tr> <tr> <td>7</td><td>8</td><td>9</td> </tr> </table> table, td { border: 1px solid black; } let table = document.querySelector('#table'); let rows = table.rows; for (let i = 0; i < rows.length; i++) { rows[i].cells[i].style.background = 'red'; }

:

See also

  • the rows property
    that contains rows of a table
  • the tHead property
    that contains thead of a table
  • the tFoot property
    that contains tfoot of a table
  • the tBodies property
    that contains tbody of a table
enru