Skip to content Skip to sidebar Skip to footer

JQuery Dynamically Create Table/tr/td Or Etc And Append Attributes

In an example I am having this structure (small example):
Test1LINK&

Solution 1:

Here's a simplified example:

  $(function() {
    var tbl = $('<table></table>').attr({ id: "bob" });
    var row = $('<tr></tr>').attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(tbl);
    $('<td></td>').text("text1").appendTo(row);
    $('<td></td>').text("Test22").prepend($('<a></a>').attr({ href: "#" }).text("LINK")).appendTo(row);        
    tbl.appendTo($(".somePlaceInHtml"));        
  });

Wrap the row portion in a loop, replace with variables and it's at least easier to maintain/read in my opinion, but I'm used to jQuery, so your mileage may vary, just an option.

A side note, since this is using .text() everywhere, it helps prevents cross-site scripting attacks within your output as well.


Solution 2:


Solution 3:

You could create a StringBuilder, much like the one in C#. Here's a snippet took from Telerik Extensions for ASP.NET MVC:

$.stringBuilder = function() {
    this.buffer = [];
};

$.stringBuilder.prototype = {

    cat: function(what) {
        this.buffer.push(what);
        return this;
    },

    string: function() {
        return this.buffer.join('');
    }
};

This way, you can have the following code:

var html = new $.stringBuilder();
for (var i in data)
    html.cat("<tr><td>").cat(i).cat("</td><td></tr>");

$('#element').append(html.string());

The benefit of this approach is that you'll have fast concatenation (array joins perform better under IE6), and you could extend the object with other useful function (say, catIf that takes a boolean expression, or rep that repeats a given string several times).


Solution 4:

Or you could instead of concatenating strings together so make use of the array.join function.

    for(var i=0;i<arr.length;i++)
    {
      arr[i] = "<tr>" + sth + "</tr>";       
    }

node.innerHTML = arr.join(''); 

Solution 5:

window.onload = function(){
    var btn = document.createElement("button");
    btn.setAttribute("id", "submit_bttn");
    btn.style.width = 125 + "px";
    btn.style.height = 50 + "px";
    btn.innerHTML = "Submit";
    document.body.appendChild(btn);

    var x = document.getElementById("submit_bttn");
    x.onclick = function(){
        alert("hi");
    }
}

Post a Comment for "JQuery Dynamically Create Table/tr/td Or Etc And Append Attributes"