mnemotronic
mnemotronic

Reputation: 1026

Building HTML table

I'm building a table from a JSON object. First step is to build the table column headers:

jq_tblRow = $('<tr>') ;
obj_Report.fieldMetadata.forEach( function(elt) {
   jq_tblRow.append('<th>' + elt.name)
}) ;

That yields a row with the column headers:

<tr><th>Item Type</th><th>Title</th> ... etc... </tr>

Is there an easier way to wrap that with TABLE & THEAD tags? Here's what I came up with eventually. It works but 2 calls to ".append()" seems awkward.

jq_tblRow = $('<table>').append( $('<thead>').append(jq_tblRow) );

I tried various combinations of

 .append('<table><thead>')

using append, appendTo, prepend, before, after, etc and the permutations thereof.

Upvotes: 0

Views: 28

Answers (1)

Rion Williams
Rion Williams

Reputation: 76547

If you already have a jQuery element, you can use the wrap() function to wrap it with some additional tags :

jq_tblRow = $('<tr>') ;
obj_Report.fieldMetadata.forEach( function(elt) {
    jq_tblRow.append('<th>' + elt.name)
});
// After you have your row in the DOM, wrap it with table/thead tags
jq_tblRow.wrap('<table><thead></thead></table>');

The wrap() function can also accept a function, if you need to handle more complex operations or preferred the look of concatenating each side :

jq_tblRow.wrap(function(){
     return '<table><thead>' + this.innerHTML + '/thead></table>';
});

Upvotes: 1

Related Questions