I have an html element that I'm replacing with a clone of itself to remove event listeners. However, I still want to interact with it after I've replaced it. Unfortunately,
node.replaceWith(node.cloneNode(true))
makes node link to an element that doesn't exist. Is there any way I can get the element that is now where it was? I know I can circumvent this by giving it an id before and querying for it after, but it feels like there should be a better way.
CodePudding user response:
You'll need to store the clone before replacing and then reassign node
.
To avoid having the clone
hanging around you can wrap the method in a function that returns the clone.
function replaceSelf(node) {
const clone = node.cloneNode(true);
node.replaceWith(clone);
return clone;
}
let node = document.getElementById('to-clone');
node = replaceSelf(node);
node.style.backgroundColor = 'cyan';
<div>
<p id="to-clone">paragraph</p>
</div>
CodePudding user response:
Try replacing this:
node = node.replaceWith(node.cloneNode(true))
with this
node.replaceWith(node.cloneNode(true))
Because replaceWith
returns undefined