Proprietà cells

La proprietà cells memorizza una collezione di celle td e th della riga tr. Si applica solo alla riga della tabella.

Sintassi

javascripttr.cells;

Esempio

Scorriamo tutte le righe della tabella utilizzando la proprietà rows, e in ogni riga scorriamo le sue celle utilizzando la proprietà 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>
javascriptlet table = document.querySelector('#table');

for (let row of table.rows) {
  for (let cell of row.cells) {
    console.log(cell);
  }
}

Esempio

Scorriamo tutte le righe della tabella utilizzando la proprietà rows e scopriamo il numero di celle in ogni riga:

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);
}

Esempio

Impostiamo lo sfondo della prima cella:

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';

Результат:

Esempio

Impostiamo lo sfondo delle celle della tabella in diagonale:

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';
}

Результат:

Vedi anche

  • la proprietà rows,
    che contiene le righe della tabella
  • la proprietà tHead,
    che contiene thead della tabella
  • la proprietà tFoot,
    che contiene tfoot della tabella
  • la proprietà tBodies,
    che contiene tbody della tabella