<!DOCTYPE html>
<html>
<head></head> <!-- This element isn't necessary, but makes it straightforward to reason about the test when debugging it. -->
<body data-debug-name="declarativeBody"></body> <!-- This element isn't necessary, but makes it straightforward to reason about the test when debugging it. -->
<!-- Notice a <script> is only executed once. -->
<script>
if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

var savedDocumentElement;
function appendBodyElementToSavedDocument()
{
    document.removeEventListener("DOMNodeRemoved", appendBodyElementToSavedDocument, false);
    savedDocumentElement.appendChild(document.createElement("body")).setAttribute("data-debug-name", "programmaticBody");
}

function insertSavedDocument()
{
    document.appendChild(savedDocumentElement); // Will execute <script id="script2">.
}

savedDocumentElement = document.documentElement;
document.addEventListener("DOMNodeRemoved", appendBodyElementToSavedDocument, false);
document.removeChild(savedDocumentElement); // Prevents <script id="script2"> from running since it won't be in the document when we fall off the end of this <script>.
window.setTimeout(insertSavedDocument, 0);
</script>
<!-- This must be in its own <script> so that we execute it (for the first time) when we re-insert it into the document in insertSavedDocument(). -->
<script id="script2">
// [1] The array |elements| will either have the form {..., <body id="declarativeBody">, ...} or {..., <body id="declarativeBody">, ..., <body id="programmaticBody">, ...}.
// The former will cause an assertion failure when we execute [2].
var elements = document.querySelectorAll("*");
for (var i = 0; i < elements.length; ++i)
    elements[i].setAttribute("name", elements[i].nodeName);

// [2] Destroy the entire document, including <body data-debug-name="declarativeBody"> and <body data-debug-name="programmaticBody">. Moving the
// following line to its own <script> and altering the execution time of this page (say, by stepping through code in a WebCore debug session)
// tends to affect the result of |elements| (see remark [1]).
document.write("PASS, removed element, with HTML attribute name, which was inserted on event DOMNodeRemoved.");
if (window.testRunner)
    testRunner.notifyDone();
</script>
</html>
