I've generated html and I need to restructuring the html using Jquery, like this:
Original:
<table id="myTableID">
<tr id="tr01">
<td>Col 1 Value</td>
</tr>
<tr id="tr02">
<td>Col 2 Value</td>
</tr>
<tr id="tr03">
<td>Col 3 Value</td>
</tr>
<tr id="tr04">
<td>Col 4 Value</td>
</tr>
</table>
Expected:
<table id="myTableID">
<tr id="tr01">
<td>Col 1 Value</td>
<td>Col 2 Value</td>
</tr>
<tr id="tr02">
<td>Col 3 Value</td>
<td>Col 4 Value</td>
</tr>
<tr id="tr03">
</tr>
<tr id="tr04">
</tr>
</table>
var tableNew = "<table id='myTableID'>"+
"<tr><td>new "+
"</td></tr>"+
"</table>";
$('#myTableID').replaceWith(tableNew);
I came up with idea with iterate and replace, any better idea?
I've generated html and I need to restructuring the html using Jquery, like this:
Original:
<table id="myTableID">
<tr id="tr01">
<td>Col 1 Value</td>
</tr>
<tr id="tr02">
<td>Col 2 Value</td>
</tr>
<tr id="tr03">
<td>Col 3 Value</td>
</tr>
<tr id="tr04">
<td>Col 4 Value</td>
</tr>
</table>
Expected:
<table id="myTableID">
<tr id="tr01">
<td>Col 1 Value</td>
<td>Col 2 Value</td>
</tr>
<tr id="tr02">
<td>Col 3 Value</td>
<td>Col 4 Value</td>
</tr>
<tr id="tr03">
</tr>
<tr id="tr04">
</tr>
</table>
var tableNew = "<table id='myTableID'>"+
"<tr><td>new "+
"</td></tr>"+
"</table>";
$('#myTableID').replaceWith(tableNew);
I came up with idea with iterate and replace, any better idea?
Share Improve this question edited Aug 15, 2018 at 7:19 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 26, 2013 at 6:50 MRizqMRizq 2712 gold badges8 silver badges21 bronze badges 2- do you have fixed number of trs – Arun P Johny Commented Dec 26, 2013 at 7:00
- @ArunPJohny: no, it was generated by server. – MRizq Commented Dec 26, 2013 at 7:03
6 Answers
Reset to default 5This one-line jQuery will do what you need. Just apply it to each row you need to reformat:
$('#tr01').append($('#tr02').contents());
There's a fiddle here
Try like this:
$( "#tr03 > td" ).appendTo( "#tr01" );
You can refer : http://api.jquery./appendTo/
My one cent - use clone to copy the td's and then move the tds around so that you preserve the events attached to them, if any.
Try
var $rows = $('#myTableID tr');
$rows.slice(0, Math.ceil($rows.length / 2)).each(function () {
var $this = $(this),
index = $this.index();
$this.append($rows.eq(index * 2).find('td'))
$this.append($rows.eq(index * 2 + 1).find('td'))
})
Demo: Fiddle
this is other option you can create/replace table by click of button
max = 2
$("button").click(function() {
var tr = $("table tr:last");
if(!tr.length || tr.find("td").length >= max)
$("table").append("<tr>");
$("table tr:last").append("<td>hi</td>");
});
<table border=1></table>
<button>hi</button>
var all_td = $('#myTableID tr').map(function () {
return $(this).html();
}).get();
$('#myTableID tr').empty().each(function(i){
var ret = all_td.slice(i*2,++i*2);
$(this).html(ret);
});
Fiddle Demo
Each
tr
will have two td