Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove an element that has been modified by outerHTML

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading