Search code examples
javaxmldomjaxp

Element created from a document but not appended: need to remove it explicitly?


I need to create a temporary DOM-element which is independent from my main document. I do it by using my main document to create an element but not appending it to the tree.

Element temporaryParentElement = document.createElement(PERMISSIONSET);

It is used to build tables in a dialog. After the dialog is closed i don't need this element anymore so I tried to remove it:

document.removeChild(temporaryParentElement);

This resulted in an exception:

org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.

If i understand it correctly the created node cannot be removed if it isn't a part of the tree. Do I need to append it to the tree and then call remove method? Or does the garbage collector take care about this element?


Solution

  • Element creation is different from appending or removing it to an existing tree. You use that document reference to create the element, but then append it to some other element. You can remove it using the reference of that element.

    The method removeChild removes an element from a tree where it was added before (with appendChild or parsed when the document was read).

    You have to find the element that represents the parent of that element in order to remove it. Suppose the parent is dialog. You would use:

    dialog.removeChild(temporaryParentElement);