@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;
}

@ 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 ; }
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
