Bug 187423

Summary: insertAdjacentHTML raises RangeException (possibly caused by node with no parent)
Product: [Applications] konqueror Reporter: Richard Smith <kde>
Component: khtmlAssignee: Konqueror Developers <konq-bugs>
Status: CONFIRMED ---    
Severity: normal    
Priority: NOR    
Version: 4.2.1   
Target Milestone: ---   
Platform: Ubuntu   
OS: Unspecified   
Latest Commit: Version Fixed In:

Description Richard Smith 2009-03-17 17:38:39 UTC
Version:            (using KDE 4.2.1)
Installed from:    Ubuntu Packages

The following javascript causes Konqueror to hit a RangeException, but it works in IE:

  document.createElement("div").insertAdjacentHTML("beforeEnd", "<span>foo</span>")

The problem appears to be caused by the usage of range.setStartBefore(node) in the implementation of insertAdjacentHTML -- this fails with RangeException if the node has no parent. The draft HTML5 spec requires insertAdjacentHTML to be a (non-throwing) no-op for a parentless node if in "beforeBegin" or "afterEnd" mode, and to operate normally in the other two modes for a parentless node:

http://www.whatwg.org/specs/web-apps/current-work/#insertadjacenthtml()
Comment 1 Richard Smith 2009-03-17 17:41:02 UTC
For reference, here's the code which ext-js uses to emulate insertAdjacentHTML:

    var N = R.ownerDocument.createRange();
    var S;
    switch (P) {
      case "beforebegin":
        N.setStartBefore(R);
        S = N.createContextualFragment(Q);
        R.parentNode.insertBefore(S, R);
        return R.previousSibling;
      case "afterbegin":
        if (R.firstChild)
          {
            N.setStartBefore(R.firstChild);
            S = N.createContextualFragment(Q);
            R.insertBefore(S, R.firstChild);
            return R.firstChild;
          }
        else
          {
            R.innerHTML = Q;
            return R.firstChild;
          }
      case "beforeend":
        if (R.lastChild)
          {
            N.setStartAfter(R.lastChild);
            S = N.createContextualFragment(Q);
            R.appendChild(S);
            return R.lastChild;
          }
        else
          {
            R.innerHTML = Q;
            return R.lastChild;
          }
      case "afterend":
        N.setStartAfter(R);
        S = N.createContextualFragment(Q);
        R.parentNode.insertBefore(S, R.nextSibling);
        return R.nextSibling;
    }
    throw "Illegal insertion point -> \"" + P + "\"";
Comment 2 Justin Zobel 2021-03-21 00:25:15 UTC
Thank you for the bug report.

As this report hasn't seen any changes in 10 years or more, we ask if you can please confirm that the issue still persists.

If this bug is no longer persisting or relevant please change the status to resolved.