diff --git a/content/base/src/nsGenericElement.cpp b/content/base/src/nsGenericElement.cpp
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -3204,25 +3204,25 @@ nsGenericElement::doInsertChildAt(nsICon
       nsCOMPtr<nsIDOMNode> adoptedKid;
       rv = domDoc->AdoptNode(kid, getter_AddRefs(adoptedKid));
       NS_ENSURE_SUCCESS(rv, rv);
 
       NS_ASSERTION(adoptedKid == kid, "Uh, adopt node changed nodes?");
     }
   }
 
+  nsMutationGuard::DidMutate();
+
+  // Do this before checking the child-count since this could cause mutations
+  mozAutoDocUpdate updateBatch(aDocument, UPDATE_CONTENT_MODEL, aNotify);
+
   PRUint32 childCount = aChildArray.ChildCount();
   NS_ENSURE_TRUE(aIndex <= childCount, NS_ERROR_ILLEGAL_VALUE);
-
-  nsMutationGuard::DidMutate();
-
   PRBool isAppend = (aIndex == childCount);
 
-  mozAutoDocUpdate updateBatch(aDocument, UPDATE_CONTENT_MODEL, aNotify);
-
   rv = aChildArray.InsertChildAt(aKid, aIndex);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = aKid->BindToTree(aDocument, aParent, nsnull, PR_TRUE);
   if (NS_FAILED(rv)) {
     aChildArray.RemoveChildAt(aIndex);
     aKid->UnbindFromTree();
     return rv;
