Removing an element through the parentNode.removeChild throws a DOM Exception 8

dom, domexception, javascript, removechild

Solution

From mdn docs:

If child is actually not a child of the element node, the method throws an exception. This will also happen if child was in fact a child of element at the time of the call, but was removed by an event handler invoked in the course of trying to remove the element (eg, blur.)

I can reproduce this error in jsfiddle

Basically, you focus the element, which triggers a remove, which triggers a blur, which moves the element, which makes the element not the parent anymore.

Problem

I have code which is roughly as follows (I removed some parts, as they are irrelevant): ``` Library.focus = function(event) { var element, paragraph; element = event.srcElement; paragraph = document.createElement("p"); paragraph.innerText = element.innerText; element.parentNode.insertBefore(paragraph, element); // Line #1 element.parentNode.removeChild(element); // Line #2 }; ``` The issue I have, is that the last call which I've numbered as line #2 throws this: ``` Uncaught Error: NOT_FOUND_ERR: DOM Exception 8 ``` Note that the previous line #1 works fine, and inserts the paragraph node before it. Element is an existing element, and both element.parentNode and element.parentNode.removeChild exist as well. I find this illogical, as element is by definition a child of its parentNode. Maybe StackOverflow will be able to help me out, here?

Original source