Do not read HTML of existing DOM elements only to insert it again into the DOM. Use existing DOM elements and copy / move them, not their HTML. This will be a lot cleaner.
Needed prerequisites
What you need is:
.detach()
for "cutting" element from DOM (without removing jQuery's data that may be attached), or .clone()
to make a copy of element you want to keep in the current place,
.after()
(or .insertAfter()
, if you prefer opposite order or arguments) for inserting element after some other element,
Example for .clone()
and for .detach()
The following example implements .clone()
and .detach()
on table's rows. In the first column you choose the row that will be copied / moved, and in the second column you choose the row after which you will paste the copied / moved row. After you have selected both rows, click on one of the links (depending on which function you want to test). See jsfiddle for demonstration.
HTML:
<table>
<tr>
<th>Which row?</th>
<th>Copy after which?</th>
<th>Original value</th>
</tr>
<tr>
<td><input type="radio" name="from" checked="checked" /></td>
<td><input type="radio" name="to" /></td>
<td>AAAAA</td>
</tr>
<tr>
<td><input type="radio" name="from" /></td>
<td><input type="radio" name="to" checked="checked" /></td>
<td>BBBBB</td>
</tr>
<tr>
<td><input type="radio" name="from" /></td>
<td><input type="radio" name="to" /></td>
<td>CCCCC</td>
</tr>
<tr>
<td><input type="radio" name="from" /></td>
<td><input type="radio" name="to" /></td>
<td>DDDDD</td>
</tr>
</table>
<a href="#" title="" id="clone">Use .clone()</a>
<a href="#" title="" id="detach">Use .detach()</a>
JavaScript (executed onLoad or onDomReady, so it can find proper DOM elements):
jQuery('#clone').on('click', function(event){
event.preventDefault();
var from_row = jQuery('[name="from"]:checked').parents('tr');
var to_row = jQuery('[name="to"]:checked').parents('tr');
to_row.after(from_row.clone());
});
jQuery('#detach').on('click', function(event){
event.preventDefault();
var from_row = jQuery('[name="from"]:checked').parents('tr');
var to_row = jQuery('[name="to"]:checked').parents('tr');
to_row.after(from_row.detach());
});
See this jsfiddle for a proof that it works.