Skip to content Skip to sidebar Skip to footer

What Are The Advantages And Disadvantages Of These Methods Of Creating Tables With Javascript?

I found two ways to create a table in JS: Using insertRow and insertCell: var table = document.getElementById ('table'); var row = table.insertRow (1); var cell = row.insertCell (

Solution 1:

If you can avoid using the elements, and just put a string into an innerHTML you'll get the best performance. Here are some different ways to create a table.

Functional Code demo

We can create some functions to generate our HTML. This code will be very fast (but could be faster). We'll assume this data for all of these examples.

var heading = ['Name', 'Points'];

vardata = [
  ["Joe", 50],
  ["Jack", 80],
  ["Doug <b>'the hammer'</b> Jones", 76]
];

We can then generate our table like so,

document.body.innerHTML = table(heading, data);
functionwrapTag(tag, html) {
  return"<" + tag + ">" + html + "</" + tag + ">";
}


functiontable(head, body) {
    returnwrapTag("table", thead(head)
    + tbody(body));
}

functionthead(head) {
  var _th = head.map(wrapTag.bind(null, "th"));
  var _tr = wrapTag("tr", _th.join("\n"));
  returnwrapTag("thead", _tr);
}

functiontbody(body) {
  return body.map(tr).join("\n");
}

functiontr(row) {
  var _td = row.map(wrapTag.bind(null, "td"));
  returnwrapTag("tr", _td.join("\n"));
}

KnockoutJS demo

In Knockout we can give it an object, and have it map directly to our HTML. With the heading and data variables defined above, we map this like so.

ko.applyBindings({heading: heading, data: data});

Our HTML makes use of the foreach binding, which iterates over an array. $data refers to the current array item.

<table><thead><trdata-bind="foreach: heading"><thdata-bind="text: $data"></th></tr></thead><tbodydata-bind="foreach: data"><trdata-bind="foreach: $data"><tddata-bind="html: $data"></td></tr></tbody></table>

AngularJS demo

Using the same data from above, we can create an AngularJS controller.

functionMyTableCtrl($scope) {
  $scope.heading = heading;
  $scope.data = data;
}

Our HTML is similar to KnockoutJS. One difference is the looping syntax, which lets us name our elements, e.g., row in data, instead of referring to elements as $data.

<tableng-controller="MyTableCtrl"><thead><tr><thng-repeat="head in heading">{{head}}</th></tr></thead><tbody><trng-repeat="row in data"><tdng-repeat="content in row"ng-bind-html-unsafe="content"></td></tr></tbody></table>

documentFragment demo

This is faster than regular DOM manipulation, and provides a nicer syntax than combining strings.

newTable = createTable(heading, data);
document.body.appendChild(newTable);
functioncreateTable(h, c) {
    var frag, table, head, body;

    frag = document.createDocumentFragment();
    table = document.createElement("table");
    head = createHeader(h);
    body = createContent(c);

    table.appendChild(head);
    table.appendChild(body);

    frag.appendChild(table);

    return frag.cloneNode(true);
}

functioncreateHeader(data) {
    var thead, rowEl, col, colEl, text, i, j;

    thead = document.createElement("thead")
    rowEl = document.createElement("tr");

    for (i = 0, j = data.length; i < j; i++) {
        col = data[i];
        colEl = document.createElement("td");
        text = document.createTextNode(col);
        colEl.appendChild(text);
        rowEl.appendChild(colEl);
    }

    thead.appendChild(rowEl);

    return thead;
}

functioncreateContent(data) {
    var content, row, rowEl, col, colEl, text, i, j, k, l;

    content = document.createElement("tbody");

    for (i = 0, j = data.length; i < j; i++) {
        row = data[i];
        rowEl = document.createElement("tr");
        for (k = 0, l = row.length; k < l; k++) {
            col = row[k];
            colEl = document.createElement("td");
            text = document.createTextNode(col);
            colEl.appendChild(text);
            rowEl.appendChild(colEl);
        }
        content.appendChild(rowEl);
    }

    return content;
}

Solution 2:

taken from this post: insertRow vs. appendChild

insertRow would be the much better. It is supported by grade A browsers and it's less verbose and a cleaner API.

insertRow might be argued as more reliable since it's DOM1.

The appendChild method is consistently faster (albeit marginally) across all tested browsers (IE6/7, FF3, Chrome2, Opera9) when operating outside of the DOM, but when trying to modify tables within the document (a more common endeavour) it's significantly slower.

In other words: definitely use insertRow.

My personal opinion is: 1 method more clear and uses native methods

Solution 3:

I actually use Mustache in day-to-day development, so you can do something like this:

Bare HTML table:

<table id="myTable"></table>

Then you can store a template in a non-JS <script> tag. You can assign an id or whatever to retrieve the element.

<script type="text/template"id="rowTemplate">
  {{#rows}}
  <tr>
    {{#items}}
    <td>
      {{.}}
    </td>
    {{/items}}
  </tr>
  {{/items}}
</script>

Retrieving the template is something like:

var template = document.getElementById('rowTemplate').innerHTML;

Then you need a data source. Mustache needs an object to do this:

vardata = {
  rows : [
    {
      items : ['hello1','world1']
    },{
      items : ['hello2','world2']
    }
  ]
}

Rendering:

var usableHTML = Mustache.render(template,data);

You can then append usableHTML to your table

document.getElementById('myTable').innerHTML = usableHTML;

Post a Comment for "What Are The Advantages And Disadvantages Of These Methods Of Creating Tables With Javascript?"