EDIT:
Working example now at jsbin.com/ivukar/10
Here is what I'm trying to do, summed up into the core steps without all the detail that would be fairly meaningless to you:
Now following these steps, let's say the HTML content of our div was "test", I would expect the following:
And yet what happens is that as soon as I make that change to the html content of the element, using for example: $('#element').html('altered');
It changes the content of the variable as well...
I cannot see why it would do that, as the variable is only ever referenced when appending it to the DOM, I am not changing the content of the variable whatsoever...
Here is a JsBin link so you can see what I mean.
Or alternatively here is the example code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
var saved = '';
function my_clone()
{
saved = $('#el').clone();
$('#output').append("<a href='#' onclick='my_remove();'>Remove version on screen</a> ----- This removes any element with the id 'el'<br>");
}
function my_remove()
{
$('#el').remove();
$('#output').append("<a href='#' onclick='my_append();'>Append clone to body</a> ----- This takes the cloned object stored in the variable 'saved' and appends it to the html body<br>");
}
function my_append()
{
$('body').append( saved );
$('#output').append("<a href='#' onclick='my_alter();'>Alter .html() of element</a>----- This alters the html of any element with the id 'el'<br>");
}
function my_alter()
{
$('#el').html('altered');
$('#output').append("<a href='#' onclick='my_remove_again();'>Remove version on screen again</a>----- This removes any element with the id 'el'<br>");
}
function my_remove_again()
{
$('#el').remove();
$('#output').append("<a href='#' onclick='my_append_again();'>Append clone to body</a> ----- This again takes the object stored in the 'saved' variable, which is separate from the DOM and should not have been affected by the html change and appends to the html body<br>");
}
function my_append_again()
{
$('body').append( saved );
}
</script>
<style>
#el {color:red;}
</style>
</head>
<body>
<div id="el">
<div id="various">Various</div>
<div id="sub">Sub
<div id="and-sub-sub">And Sub-Sub</div>
</div>
<div id="elements">Elements</div>
</div>
<br><br>
<div id="output">
<a href="#" onclick="my_clone();">Clone</a> ------ This stores the clone into a global variable called 'saved'<br>
</div>
</body>
</html>
Could anyone tell me where I am going wrong here?
Thanks.
The problem was that you were assigning the actual DOM element to saved
rather than the HTML content.
An old trick:
saved = $("#el").clone().wrap('<div/>').parent().html();
You first wrap the clone in a parent div
whose HTML you return.
Updated JSBIN http://jsbin.com/ivukar/4
Reference: Get DOM element as string
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