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>
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
use wrapAll instead of wrap
$('#myTable tr:has(th)').wrapAll('<thead></thead>');
$("#myTable thead").prependTo("#myTable")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With