W3C home > Mailing lists > Public > public-webapps@w3.org > January to March 2015

Re: oldNode.replaceWith(...collection) edge case

From: Jonas Sicking <jonas@sicking.cc>
Date: Thu, 22 Jan 2015 02:43:43 -0800
Message-ID: <CA+c2ei9cSXz2c7UJ8oojOs_SoN-GXA7PAjsLiaH2xeb9z3jQqg@mail.gmail.com>
To: Glen Huang <curvedmark@gmail.com>
Cc: Webapps WG <public-webapps@w3.org>, Anne van Kesteren <annevk@annevk.nl>
On Jan 17, 2015 8:20 PM, "Glen Huang" <curvedmark@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
Received on Thursday, 22 January 2015 10:44:40 UTC

This archive was generated by hypermail 2.3.1 : Friday, 27 October 2017 07:27:25 UTC