Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert th in thead

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?

like image 639
Moazzam Khan Avatar asked Feb 21 '13 10:02

Moazzam Khan


People also ask

How do you make a th in Javascript?

createElement("TH"); if (arguments. length == 0 || index == -1 || index == this. cells. length) { return this.

What is the difference between thead and th?

<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.

Do you need TR in thead?

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.

What is Tablehead element?

<thead>: The Table Head element. The <thead> HTML element defines a set of rows defining the head of the columns of the table.


2 Answers

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 
like image 195
steven Avatar answered Sep 22 '22 02:09

steven


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

like image 27
Minko Gechev Avatar answered Sep 22 '22 02:09

Minko Gechev