7

How do I add <thead> and <tbody> this using jQuery?

the problem is my table has 1 or 2 th rows?

$('#myTable tr:has(th)').wrap('<thead></thead>');

<table id="myTable">

<tr><th>1</th><th>2</th><th>3</th><th>4</th></tr>
<tr><th>1</th><th>2</th><th>3</th><th>4</th></tr>

<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>  
</table>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Hello-World
  • 9,277
  • 23
  • 88
  • 154
  • 2
    a [table header](http://www.w3.org/wiki/HTML/Elements/th) generally has one `thead` element as a sibling of `tbody`, not multiple heads inside a row. – jbabey Oct 08 '12 at 12:40
  • @jbabey not every browser adds a thead element. They do add a tbody. – epascarello Oct 08 '12 at 12:56

3 Answers3

16

What you need to do is remove the rows and append them to a thead element

var myTable = jQuery("#myTable");
var thead = myTable.find("thead");
var thRows =  myTable.find("tr:has(th)");

if (thead.length===0){  //if there is no thead element, add one.
    thead = jQuery("<thead></thead>").appendTo(myTable);    
}

var copy = thRows.clone(true).appendTo("thead");
thRows.remove();

jsFiddle exmaple

epascarello
  • 204,599
  • 20
  • 195
  • 236
7

use wrapAll instead of wrap

$('#myTable tr:has(th)').wrapAll('<thead></thead>');​
$("#myTable thead").prependTo("#myTable")
YogeshWaran
  • 2,291
  • 4
  • 24
  • 32
0
function createTable(data) {
    var str = "";
    str += '<table><thead>';
    str += '<tr><td>Pos</td><td>Ref</td></tr></thead><tbody>';
    for (var item in data.recentList) {
        str += '<tr>';
        for (idata in data.recentList[item]) {
            str += '<td>' + data.recentList[item][idata] + '</td>';
        }
        str += '</tr>';
    }
    str += '</tbody></table>';
    $('body').append(str);
}

Working version that creates a table from an array

Andrew Day
  • 563
  • 10
  • 23