Reputation: 4821
What I am trying to accomplish
I am working on something that allows the user to alter an svg file based on input, such as text, bold, italic, ect. Then, I want the user to be able to revert to the original template without having to reload the file again.
I essentially want a copy of the object.
What I've tried
// Get template
$.get('../path/to/file.svg', function(svg_template)
{
var svg = svg_template.getElementsByTagName('svg')[0];
// Alter template
$('#bold').click( function() {
svg.text.attr('font-weight', 'bold');
});
// Return to original template
$('#reset').click( function() {
var svg = svg_template.getElementsByTagName('svg')[0];
});
}, 'xml');
And I've tried this in many variations.
var svg = svg_template.getElementsByTagName('svg')[0];
var svgcopy = svg_template.getElementsByTagName('svg')[0];
// ...
$('#reset').click( function() {
svg = svg = svg_copy;
});
I've also read up on something in jQuery called extend()
, but I'm getting "Illegal invocation"
var svg = svg_template.getElementsByTagName('svg')[0];
var svg_copy = jQuery.extend(true, {}, svg);
// ...
$('#reset').click( function() {
svg = svg = svg_copy;
});
I've also looked at clone()
, however that requires a copy of it exists in the DOM, which is much slower, requires me to hide the object, and select the object from the Dom when I need it, and even still, how do I select it without making yet another clone of it, because placing a variable equal to the clone puts me in the same position I started in.
Only relevant question I could find is unanswered.
Storing static copies of jQuery objects
Behavior I get
Instead of a copy, each time I make a variable equal to that object, it acts as a pointer to it, a representative of that object, and any alteration to one one object affects other variables that are also equal to that object.
My question
How can I make a copy of a jQuery object?
Upvotes: 1
Views: 69
Reputation: 4821
Although Kogicon's answer did not work, it did inspire my solution, which I'm posting here for anyone else who faces this issue. I serialized the object, and then unserialize it whenever I need a copy of it. This is quick and simple to understand. Credit goes to Kogicon.
$.get(template_path, function(svg_template)
{
var svg_original = svg_template.getElementsByTagName('svg')[0];
var serializer = new XMLSerializer();
var svg_copy = serializer.serializeToString(svg_original);
var svg = $.parseXML(svg_copy); svg = $.parseXML(svg_copy);
svg = svg.getElementsByTagName('svg')[0];}, 'xml');
}
Upvotes: 0
Reputation: 76
If you're just looking to save the data in an element, I would suggest using var svg = $('svg');
to select the svg, then using the var svg_save = svg.html();
to get all of the innerHTML as a string. Then you can reset by using svg.html(svg_save);
. Hope it helps!
Upvotes: 2