Table cells collection
Definition and usage
cells
The collection returns a collection of all <td> or <th> elements in the table.
Note:Elements in the collection are sorted in the order they appear in the source code.
Tip:Use rows collection Returns a collection of all <tr> elements in the table.
Tip:Use insertRow() method Create a new row (<tr>).
Tip:Use deleteRow() method Delete row.
Tip:Use insertCell() method Create a new cell (<td>).
Tip:Use deleteCell() method Delete cell.
See also:
HTML Reference Manual:HTML <td> Tag
HTML Reference Manual:HTML <th> Tag
JavaScript Reference Manual:HTML DOM TableData Object
JavaScript Reference Manual:HTML DOM TableHeader Object
Instance
Example 1
Display the number of cells in the first row:
var x = document.getElementById("myTable").rows[0].cells.length;
The result of x will be:
2
Example 2: [index]
Output the innerHTML of the first cell in the first row of the table:
alert(document.getElementById("myTable").rows[0].cells[0].innerHTML);
Example 3: item(index)
Output the innerHTML of the first cell in the first row of the table:
alert(document.getElementById("myTable").rows[0].cells.item(0).innerHTML);
Example 4: namedItem(id)
Output the innerHTML of the cell with id="myTd" in the first row of the table:
alert(document.getElementById("myTable").rows[0].cells.namedItem("myTd").innerHTML);
Example 5
Change the content of the first table cell:
var x = document.getElementById("myTable").rows[0].cells; x[0].innerHTML = "NEW CONTENT";
Syntax
tableObject.cells
Property
Property | Description |
---|---|
length |
Returns the number of <td> and/or <th> elements in the collection. Note:This property is read-only. |
Method
Method | Description |
---|---|
[index] |
Returns the <td> and/or <th> element at the specified index within the collection (starting from 0). Note:Returns null if the index is out of range. |
item(index) |
Returns the <td> and/or <th> element at the specified index within the collection (starting from 0). Note:Returns null if the index is out of range. |
namedItem(id) |
Returns <td> and/or <th> elements from the collection with the specified id. Note:Returns null if the id does not exist. |
Technical Details
DOM Version: | Core Level 2 Document Object |
---|---|
Return value: |
The HTMLCollection object represents all <td> and/or <th> elements within a <tr> element. Elements in the collection are sorted in the order they appear in the source code. |
Browser Support
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support |