Add "thead" to a table created with createElement

4

I have the following code, which creates a table, using createElement() :

var context = document.createElement('table');
var row; context.className = 'table';

row = context.insertRow();
row.insertCell().innerHTML = 'foo';
row.insertCell().innerHTML = 'bar';

When I inspected the element, I noticed that it creates <tbody> , but not <thead> .

Question

How do I add <thead> and its <th> elements?

    
asked by anonymous 18.01.2014 / 21:19

1 answer

5

You can use this:

var header = context.createTHead();
var row = header.insertRow();

Example

With jQuery it is simpler since it is allowed to create elements directly and add them to the table

var header = $('<thead></thead>');
var row = $('<tr></tr>');
var th = $('<th></th>').html('Cabeça');
row.append(th);
header.append(row);
context.append(header);

Example

If you want to insert many rows / columns with simple javascript, here is an example to add multiple rows and columns:

var context = document.createElement('table');
context.className = 'table';
var header = context.createTHead();
var row = header.insertRow();


for (var i = 0; i < colunas; i++) {
    var th = document.createElement('th');
    th.innerHTML = 'Coluna ' + i;
    row.appendChild(th);
};

var body = context.appendChild(document.createElement('tbody'))
for (var i = 0; i < linhas; i++) {
    var row;
    row = body.insertRow();
    for (var j = 0; j < colunas; j++) {
        row.insertCell().innerHTML = 'foo';
    };
};

context.appendChild(body);
document.body.appendChild(context);
    
18.01.2014 / 21:23