On Jan 17, 2015 8:20 PM, "Glen Huang" <curvedm...@gmail.com> wrote:
>
> Oh crap. Just realized saving index won't work if context node's previous
siblings are passed as arguments. Looks like inserting transient node is
still the best way.

The simplest way to write this method would seem to me to be something like:

Node.prototype.replaceWith = function(collection) {
  if (collection instanceof Node)
    collection = [collection];

  var following = this.nextSibling;
  var parent = this.parentNode;
  parent.removeChild(this);
  for (node of collection) {
    if (node == following) {
      following = following.nextSibling;
      continue;
    }

    if (node.nodeType == FRAGMENT) {
      var last = node.lastChild;
    }

    parent.insertBefore(node, following);

    if (node.nodeType == FRAGMENT) {
      following = last.nextSibling;
    }
  }
}

In general I agree that it feels unintuitive that you can't replace a node
with a collection which includes the node itself. So the extra line or two
of code seems worth it.

/ Jonas

Reply via email to