I have an element in the DOM that I update its HTML using outerHTML property, but I can’t remove it using a method like remove().
<div id="element">Element</div>
<div id="remove">Removed element</div>
const element = document.getElementById("element");
const removedElement = document.getElementById("remove");
element.outerHTML = "<div>First</div>";
element.remove();
removedElement.remove();
In my example, element gets updated using outerHTML, but I can’t remove it using remove() method while I can remove removedElement easily.
That’s not expected. Am I missing something in the specification? I’ve looked in W3C, but it’s very advanced for me.
And, MDN doesn’t mention anything about that (unless I have missed something). I’m OK with either other methods to update HTML content or to remove elements from the DOM, but I’d love to know the original reason.
>Solution :
According to MDN:
while the element will be replaced in the document, the variable whose outerHTML property was set will still hold a reference to the original element
The element variable still contains <div id="element">Element</div>, but is no longer in the document tree, so calling remove() has no effect.
const element = document.getElementById("element");
element.outerHTML = "<div>First</div>";
console.log(element); // still has original contents
<div id="element">Element</div>
To keep the reference to the new element, consider using Element#replaceWith and document.createElement.
const element = document.getElementById("element");
const newEl = Object.assign(document.createElement('div'), {textContent: 'First'});
element.replaceWith(newEl);
console.log(element);
console.log(newEl);
newEl.remove();
<div id="element">Element</div>