I want to insert a th
tag inside tr
of thead
element of a table. I am using insertCell
method of row object created under
You can also use the insertCell method as originally requested. You just have to change the outerHTML to overwrite the <td>
created by the insertCell method:
var table = document.createElement("TABLE")
var row = table.insertRow(0);
row.insertCell(0).outerHTML = "<th>First</th>"; // rather than innerHTML
To match the example given:
HTML
<table id="table">
<thead>
<tr>
<th>First</th>
</tr>
<thead>
</table>
Javascript
var tr = document.getElementById('table').tHead.children[0];
tr.insertCell(1).outerHTML = "<th>Second</th>" // some browsers require the index parm -- 1
You can add this functionality to the native HTMLTableRowElement by changing it's prototype:
HTMLTableRowElement.prototype.insertCell = (function(oldInsertCell) {
return function(index) {
if (this.parentElement.tagName.toUpperCase() == "THEAD") {
if (index < -1 || index > this.cells.length) {
// This case is suppose to throw a DOMException, but we can't construct one
// Just let the real function do it.
} else {
let th = document.createElement("TH");
if (arguments.length == 0 || index == -1 || index == this.cells.length) {
return this.appendChild(th);
} else {
return this.insertBefore(th, this.children[index]);
}
}
}
return oldInsertCell.apply(this, arguments);
}
})(HTMLTableRowElement.prototype.insertCell);
After this code is run, any new HTMLTableRowElements ("td" tags) will check to see if the parent is a thead tag. If so, it will do the same functionality as insertCell, but using a th tag instead. If not, it will just use the original insertCell functionality.
document.querySelector("thead > tr").insertCell(); // inserts a th into a tr inside a thead
document.querySelector(":not(thead) > tr").insertCell(); // inserts a td into a tr not inside a thead
Note that it is generally not recommended to extend the native objects.
You can do it with vanilla JavaScript. Try this:
HTML
<table id="table">
<thead>
<tr>
<th>First</th>
</tr>
<thead>
</table>
JavaScript
var tr = document.getElementById('table').tHead.children[0],
th = document.createElement('th');
th.innerHTML = "Second";
tr.appendChild(th);
Here is an example http://codepen.io/anon/pen/Bgwuf
Use table.tHead.children[0].appendChild(document.createElement("th"))
method instead. Basically you have to create a th
at runtime and insert it into your thead.