Add "thead" to a table created with createelement

Asked

Viewed 429 times

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 inspecting the element, I realized that it creates <tbody>, but not the <thead>.

Question

How to add the <thead> and its elements <th>?

1 answer

5


You can use it like 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 it 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);
  • 1

    I use a jQuery.each() to popular the table with data coming by Ajax.

  • @Calebeoliveira, I added info on how to do with jQuery. If you post your code here I can adapt the answer better

  • 1

    In my case, simple javascript is more visually clean. It’s good like this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.