cells property

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

Syntax

javascripttr.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:

html<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>
javascriptlet 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:

html<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>
javascriptlet 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:

html<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>
csstable, td {
  border: 1px solid black;
}
javascriptlet table = document.querySelector('#table');
table.rows[0].cells[0].style.background = 'red';

Результат:

Example

Let's set a background of diagonally table cells:

html<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>
csstable, td {
  border: 1px solid black;
}
javascriptlet 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