Reputation: 502
I have this:
div#origin
span
span
div#final
I need to detach the content from "origin", add some extra span's and then append all to "final" with jQuery.
How I can do that. I was searching but maybe I did it with wrong terms because I don't get the answer.
Thanks to any further help.
Upvotes: 0
Views: 177
Reputation: 9593
You can use append to move the children and the newly defined elements to their new parent element:
var children = $('#origin').children();
var extra = '<span class="extra">Extra Stuff</span>';
// This will move the children to the new parent and add the extra variable defined
$('#final').append(children, extra);
Another option that could possibly add more flexibility depending on what your needs are is to clone the children and append it when you need to:
JS Fiddle - clone() and append()
var children = $('#origin').children();
var cloned = children.clone(true,true); // Store a copy of the children to be appended
var extra = '<span class="extra">Extra Stuff</span>';
children.remove(); // Remove the old non-cloned children
$('#final').append(cloned, extra); // append cloned and extra elements
Upvotes: 1
Reputation:
This should do the trick:
var data1 = $("#span1").text(),
data2 = $("#span2").text(),
other = "Whatever else you wanted"
$("#span1").remove()
$("#span2").remove()
$("#final").append("<span>" + data1 + "</span>")
$("#final").append("<span>" + data2 + "</span>")
$("#final").append("<span>" + other + "</span>")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="orgin">
<span id="span1">span</span>
<span id="span2">span</span>
</div>
<div id="final">
</div>
Upvotes: 0