I have SVG elements on the page. I try to change one then revoke changes:
const button1 = document.getElementById('button1');
const button2 = document.getElementById('button2');
var elements = new Map();
var copy;
button1.addEventListener('click', event => {
var svgns = "http://www.w3.org/2000/svg",
container = document.getElementById( 'cont' );
for (var x = 0; x < 500; x += 50) {
var circle = document.createElementNS(svgns, 'circle');
circle.setAttributeNS(null, 'cx', x);
circle.setAttributeNS(null, 'cy', x);
circle.setAttributeNS(null, 'r', 50);
circle.setAttributeNS(null, 'style', 'fill: none; stroke: blue; stroke-width: 1px;' );
elements.set(x, circle);
container.appendChild(circle);
}
});
button2.addEventListener('click', event => {
let element = elements.get(50);
copy = element.cloneNode(true);
element.style.fill = "red";
});
button3.addEventListener('click', event => {
let element = elements.get(50);
element = copy;
//console.log(element);
});
<button id="button1">Build</button>
<button id="button2">Change</button>
<button id="button3">Revert</button>
<svg id="cont" height="1000" width="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>
element = copy is only going to change a reference to the DOM element, but not the DOM itself. For that you need to use the DOM API.
So replace that assignment with:
element.replaceWith(copy);
const button1 = document.getElementById('button1');
const button2 = document.getElementById('button2');
var elements = new Map();
var copy;
button1.addEventListener('click', event => {
var svgns = "http://www.w3.org/2000/svg",
container = document.getElementById( 'cont' );
for (var x = 0; x < 500; x += 50) {
var circle = document.createElementNS(svgns, 'circle');
circle.setAttributeNS(null, 'cx', x);
circle.setAttributeNS(null, 'cy', x);
circle.setAttributeNS(null, 'r', 50);
circle.setAttributeNS(null, 'style', 'fill: none; stroke: blue; stroke-width: 1px;' );
elements.set(x, circle);
container.appendChild(circle);
}
});
button2.addEventListener('click', event => {
let element = elements.get(50);
copy = element.cloneNode(true);
element.style.fill = "red";
});
button3.addEventListener('click', event => {
let element = elements.get(50);
element.replaceWith(copy);
});
<button id="button1">Build</button>
<button id="button2">Change</button>
<button id="button3">Revert</button>
<svg id="cont" height="1000" width="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>