in JS by (15.1k points)
0 like 0 dislike
11 views

I want to insert a th tag inside tr element of a table. I am using the standard JS method insertCell for row object of table, which is actually inserting td tag. Is there any JavaScript solution to insert in table a th tag, instead td, without using any JS library?

How I can to insert th (table header) HTML element in table on JavaScript?

Suitable search queries for this question
  • js table insert th
  • js insert th in table
  • js insert th cell in table
  • js insertCell insert th instead td

1 Answer

0 like 0 dislike
by (15.1k points)

Yes, sure, you can insert the th element in table on pure JS, by next ways:

Insert new th cells in exist rows

Insert th cell in exist row in thead:

document.getElementById('tbl').tHead.children[0].appendChild(document.createElement('th')); document.getElementById('tbl').tHead.children[0].insertCell(-1).outerHTML = '<th>bar</th>';

Insert th cell in exist row in tbody:

document.getElementById('tbl').tBodies[0].children[0].appendChild(document.createElement('th')); document.getElementById('tbl').tBodies[0].children[0].insertCell(-1).outerHTML = '<th>foo</th>';

Insert new rows and th cells

Insert row with th cell in table:

document.getElementById('tbl').insertRow(-1).insertCell(-1).outerHTML = '<th>foo</th>';

Solution with creating exactly th element:

var th = document.createElement('th'); th.innerHTML = 'foo'; document.getElementById('tbl').insertRow(-1).insertCell(-1).outerHTML = th.outerHTML;

Pure properly solution with DOM changing with help special methods, w/o manually directly markup modification by use innerHTML and outerHTML properties:

var th = document.createElement('th'); th.appendChild(document.createTextNode('foo')); document.getElementById('tbl').insertRow(-1).appendChild(th);

Please log in or register to answer this question.