mashet
mashet

Reputation: 876

How to append row into a table without using the <tr> tag?

I know how to append a new row into a table using jquery. The simpliest way to do that is using tags <tr>:

function insertRow(data, reportNumber) {  
    var guid = $(data).find('ID').text();  
    var portId = $(data).find('PortID').text();  
    var status = $(data).find('Status').text();  
    $('#gvwCashRegisterList').append(  
            "<tr class=\"cashRegisterRow\"><td><input type=\"checkbox\" value=\"" + guid +   "\"/></td><td>" + new Date().toLocaleString() + "</td><td>" + guid + "</td>  <td></td><td>" + reportNumber + "</td><td>" + portId + "</td><td>" + status + "</td><td><a   href=\"CashRegisterList.aspx\">Select</a></td></tr>"  
        );  
}

Is there any known way to do that without using the tags <tr>? For example : jQuery functions, plugins or libraries?

Upvotes: 0

Views: 3448

Answers (3)

danwellman
danwellman

Reputation: 9273

There's an even cleaner way using 1.4+ syntax:

$("table").append(
    // create new tr element
    $("<tr></tr>", {
        "class": "newClass", // set its class
        html: $("<td></td>", { // create a td element within the tr
          text: "Table cell" // add text content
        })
    });
});

Now everything is neatly encapsulated within the new tr object. Attributes and content are defined in the second argument (object literal) passed to the $() method ;)

Upvotes: 2

Purag
Purag

Reputation: 17071

Only the <tr> tag can generate a table row in HTML—there's no other way to replicate their behavior with another tag in a table.

There's a cleaner way to append table rows, though:

$("table tbody").append(
    $("<tr>") // create new tr element
        .attr("class","newTR") // set its class
        .append(
            $("<td>") // create a new td element within the tr
                .html("But this is new!") // set its content
        )
);

Example.

Be very mindful of the lack of semicolons ; (after the second append(), for example, and the html()).

Upvotes: 5

isNaN1247
isNaN1247

Reputation: 18099

In jQuery you can do this:

$('<tr class="myclass" />')
    .append($('<td />').html('whatever here'))
    .appendTo('table');

Upvotes: 0

Related Questions