0

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.

2
  • There are other methods that could do the same thing but it all fits into a one liner...how much simpler would you expect it to get? Commented Oct 4, 2016 at 3:05
  • Do note however that jq_tblRow is now actually the whole table not the row you appended...not sure what that assignment is intended for Commented Oct 4, 2016 at 3:07

1 Answer 1

1

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>';
});
Sign up to request clarification or add additional context in comments.

1 Comment

Works for me. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.