Reputation: 31
Take a simple table, like:
<table id="fu">
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
I get the top element "fu" and then I get to the 0,0 cell one of two ways.
fu.children[0].children[0].cells[0]
or
fu.children[0].children[0].children[0]
I understand the difference between children and childNodes, but cells and children seem to be identical. If I look at them in the debugger I see:
fu.children[0].children[0].
...
cells: HTMLCollection(2) [th, th]
childElementCount: 2
childNodes: NodeList(5) [text, th, text, th, text]
children: HTMLCollection(2) [th, th]
...
What is the difference and should I be using .cells or .children or doesn't it matter? It doesn't seem to matter but I worry that there might be situations where they differ that would break my code.
thanks
Upvotes: 3
Views: 853
Reputation: 581
cells
and children
are not the same.
cells
only includes th
and td
, whereas children
can include any HTMLElement.
If you run this in Chrome:
<html>
<body>
<table id="table1">
<tr>
<td>CellOne</td>
<td>CellTwo</td>
<script>console.log('hello world');</script>
<td>CellThree</td>
</tr>
</table>
<script>
let concat = '';
let row0_children = document.getElementById("table1").rows[0].children;
concat = '>>> Summary: \n' + 'Length of row_0.children = ' + row0_children.length + ', including:\n';
for (const v of row0_children) concat += '-' + v.innerText + '\n';
console.log(concat);
let row0_cells = document.getElementById("table1").rows[0].cells;
concat = '>>> Summary: \n' + 'Length of row_0.cells = ' + row0_cells.length + ', including:\n';
for (const v of row0_cells) concat += '-' + v.innerText + '\n';
console.log(concat);
</script>
</body>
</html>
>>> Summary:
Length of row_0.children = 4, including:
-CellOne
-CellTwo
-console.log('hello world');
-CellThree
>>> Summary:
Length of row_0.cells = 3, including:
-CellOne
-CellTwo
-CellThree
Upvotes: 3
Reputation: 944005
Since the only child elements a table row can have are cells, there is no practical difference between the two when used on a tr
element.
The children
property applies to all elements in the DOM, but is from a newer specification that cells
so isn't supported on some ancient and obsolete browsers.
Upvotes: 1