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 table.tHead
, which is actually inserting td
. Is there any JavaScript solution without using any JS library?
Update Currently I am using something same as solution provided by Minko Gechev and gaurav. I want to know if there is any clean solution like using insertCell
?
createElement("TH"); if (arguments. length == 0 || index == -1 || index == this. cells. length) { return this.
<th> tag is used to give header in the cell of a table in HTML whereas <thead> tag is used to give the header of a group of a table.
Note: The <thead> element must have one or more <tr> tags inside. The <thead> tag must be used in the following context: As a child of a <table> element, after any <caption> and <colgroup> elements, and before any <tbody>, <tfoot>, and <tr> elements.
<thead>: The Table Head element. The <thead> HTML element defines a set of rows defining the head of the columns of the table.
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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With