A
A
alexander rodin2018-02-04 11:46:38
JavaScript
alexander rodin, 2018-02-04 11:46:38

How to wrap table in tbody + thead using JS?

Hey!
I have a table that is generated from JSON using JS, here is the code (I did not write it myself, I found it):

'use strict';
    var _table = document.createElement('table'),
        _tr = document.createElement('tr'),
        _th = document.createElement('th'),
        _td = document.createElement('td');

    // Builds the HTML Table out of myList json data from Ivy restful service.
    function createTable(arr) {
        var table = _table.cloneNode(false),
            columns = addAllColumnHeaders(arr, table);
        for (var i = 0, maxi = arr.length; i < maxi; ++i) {
            var tr = _tr.cloneNode(false);
            for (var j = 0, maxj = columns.length; j < maxj; ++j) {
                var td = _td.cloneNode(false);
                var cellValue = arr[i][columns[j]];
                td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
                tr.appendChild(td);
            }
            table.appendChild(tr);
        }
        return table;
    }

    // Adds a header row to the table and returns the set of columns.
    // Need to do union of keys from all records as some records may not contain
    // all records
    function addAllColumnHeaders(arr, table) {
        var columnSet = [],
            tr = _tr.cloneNode(false);
        for (var i = 0, l = arr.length; i < l; i++) {
            for (var key in arr[i]) {
                if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {
                    columnSet.push(key);
                    var th = _th.cloneNode(false);
                    th.appendChild(document.createTextNode(key));
                    tr.appendChild(th);
                }
            }
        }
        table.appendChild(tr);
        return columnSet;
    }


    document.getElementById('employees').appendChild(createTable(tableData)).id = 'myTable';

Thus, I get an ordinary table, but I would like to define the table header and table body, the table looks like this:
5a76c84b73441709381678.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question