Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add <thead> and add <tbody>

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>
like image 373
Hello-World Avatar asked Oct 08 '12 12:10

Hello-World


2 Answers

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 ​

like image 132
epascarello Avatar answered Oct 03 '22 12:10

epascarello


use wrapAll instead of wrap

$('#myTable tr:has(th)').wrapAll('<thead></thead>');​
$("#myTable thead").prependTo("#myTable")
like image 34
YogeshWaran Avatar answered Oct 03 '22 13:10

YogeshWaran