Reputation: 3334
I want to add <th>
headers to a <table>
that does not have an "id"
but which is in a <div>
having a known "id"
so I traverse the DOM to find it:
// search <table>
var c = document.getElementById("tablediv").children;
var i; for(i = 0; i < c.length; i++)
{ Output("- " + c[i].nodeName + "<br>"); // show progress
if(c[i].nodeName == "TABLE") break; }
var tablex = c[i]; // that's the right object
var columns = tablex[0].length; // "TypeError: tablex[0] is undefined"
var row = tablex.insertRow(-1);
for(var i = 0; i < columns; i++)
{ var headerCell = document.createElement("TH");
headerCell.innerHTML = tablex[1][i];
row.appendChild(headerCell);
}
And when tablex[0].length;
is run it raises "TypeError: tablex[0] is undefined".
I guess var tablex
is an incorrect way to assign c[i];
.
Can you please let me know how to do it right?
NOTE: the first TD row of the table contains the column titles so either we convert this row to TH or we fetch titles and delete the TD row after a TH row was inserted.
Upvotes: 1
Views: 109
Reputation: 6299
First of all, you don't need to traverse like that. It's easier to query the table directly with querySelector('#tablediv table')
. Notice the use of querySelector instead of querySelectorAll, this returns first table inside the node with requested ID.
So the final code would look like this:
var table = document.querySelector('#tablediv table');
// Here you can add check if the table was found (not null) - I'll leave that to you
var firstRow = table.querySelector('tr');
var columns = firstRow.querySelectorAll('td'); // Or th if you have a header cells
console.log(`Number of columns: ${columns.length}`);
var headerRow = document.createElement('tr');
firstRow.parentNode.insertBefore(headerRow, firstRow);
for(var i = 0; i < columns.length; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columns[i].innerHTML;
headerRow.appendChild(headerCell);
}
firstRow.remove();
Upvotes: 4
Reputation: 68
Considering the fact that tablex
would optimally be a HTMLTableElement, tablex[0]
is not defined.
Upvotes: 0