question: @ Override public Node insertBefore ( Node newChild , Node refChild ) throws DOMException { int type = newChild . getNodeType ( ) ; if ( errorChecking ) { if ( needsSyncChildren ( ) ) { synchronizeChildren ( ) ; } if ( ( type == Node . ELEMENT_NODE && docElement != null ) || ( type == Node . DOCUMENT_TYPE_NODE && docType != null ) ) { String msg = DOMMessageFormatter . formatMessage ( DOMMessageFormatter . DOM_DOMAIN , "HIERARCHY_REQUEST_ERR" , null ) ; throw new DOMException ( DOMException . HIERARCHY_REQUEST_ERR , msg ) ; } } if ( newChild . getOwnerDocument ( ) == null && newChild instanceof DocumentTypeImpl ) { ( ( DocumentTypeImpl ) newChild ) . ownerDocument = this ; } super . insertBefore ( newChild , refChild ) ; if ( type == Node . ELEMENT_NODE ) { docElement = ( ElementImpl ) newChild ; } else if ( type == Node . DOCUMENT_TYPE_NODE ) { docType = ( DocumentTypeImpl ) newChild ; } return newChild ; }
target:  Since a Document may contain at most one top-level Element child, and at most one DocumentType declaraction, we need to subclass our add-children methods to implement this constraint. Since appendChild() is implemented as insertBefore(,null), altering the latter fixes both. <p/> While I'm doing so, I've taken advantage of the opportunity to cache documentElement and docType so we don't have to search for them. <p/> REVISIT: According to the spec it is not allowed to alter neither the document element nor the document type in any way