<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>Test bug 1799354</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" href="/tests/SimpleTest/test.css"/>
  <script>
    add_task(t => {
      let root = document.createElement("div");
      root.innerHTML = "<div id='a'>text<div id='b'>text2</div></div>";
      const a = root.firstChild;
      const b = a.lastChild;
      const txt = b.previousSibling;
      const txt2 = b.firstChild;
      let events = [];
      function listener(event) {
        events.push(event);
      }
      root.addEventListener("DOMNodeRemoved", listener);

      // Test 1, replace current children with an element.
      b.replaceChildren(txt);
      is(events.length, 2, "Should have got two DOMNodeRemoved events");
      // replaceChildren removes first all the child nodes of b and then when
      // a new child is added to it, that child is removed from its original parent.
      // https://dom.spec.whatwg.org/commit-snapshots/6b3f055f3891a63423bf235d46f38ffdb298c2e7/#concept-node-replace-all
      is(events[0].target, txt2);
      is(events[0].relatedNode, b);
      is(events[1].target, txt);
      is(events[1].relatedNode, a);

      // Test 2, replace current children with a document fragment.
      events = [];
      const df = document.createDocumentFragment();
      const dfChild1 = document.createElement("div");
      df.appendChild(dfChild1);
      const dfChild2 = document.createElement("div");
      df.appendChild(dfChild2);
      df.addEventListener("DOMNodeRemoved", listener);

      b.replaceChildren(df);
      is(events.length, 3, "Should have got three DOMNodeRemoved events");
      is(events[0].target, txt);
      is(events[0].relatedNode, b);
      is(events[1].target, dfChild1);
      is(events[1].relatedNode, df);
      is(events[2].target, dfChild2);
      is(events[2].relatedNode, df);

      // Test 3, replace current children with multiple elements.
      events = [];
      const rootChild1 = document.createElement("div");
      root.appendChild(rootChild1);
      const rootChild2 = document.createElement("div");
      root.appendChild(rootChild2);
      // Note, if replaceChildren gets more than one parameter, it moves the nodes
      // to a new internal document fragment and then removes the current children.
      b.replaceChildren(rootChild1, rootChild2);
      is(events.length, 4, "Should have got four DOMNodeRemoved events");
      is(events[0].target, rootChild1);
      is(events[0].relatedNode, root);
      is(events[1].target, rootChild2);
      is(events[1].relatedNode, root);
      is(events[2].target, dfChild1);
      is(events[2].relatedNode, b);
      is(events[3].target, dfChild2);
      is(events[3].relatedNode, b);
    });
  </script>
</head>
<body>
<p id="display"></p>
<div id="content" style="display: none"></div>
<pre id="test"></pre>
</body>
</html>
