W3cubDocs

/DOM

ChildNode.replaceWith

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The ChildNode.replaceWith() method replaces this ChildNode in the children list of its parent with a set of Node or DOMString objects. DOMString objects are inserted as equivalent Text nodes.

Syntax

[Throws, Unscopable] 
void ChildNode.replaceWith((Node or DOMString)... nodes);

Parameters

nodes
A set of Node or DOMString objects to replace.

Exceptions

Examples

Using replaceWith()

var parent = document.createElement("div");
var child = document.createElement("p");
parent.appendChild(child);
var span = document.createElement("span");

child.replaceWith(span);

console.log(parent.outerHTML);
// "<div><span></span></div>"

ChildNode.replaceWith() is unscopable

The replaceWith() method is not scoped into the with statement. See Symbol.unscopables for more information.

with(node) { 
  replaceWith("foo");
}
// ReferenceError: replaceWith is not defined 

Polyfill

You can polyfill the replaceWith() method in Internet Explorer 10+ and higher with the following code:

function ReplaceWithPolyfill() {
  'use-strict'; // For safari, and IE > 10
  var parent = this.parentNode, i = arguments.length, currentNode;
  if (!parent) return;
  if (!i) // if there are no arguments
    parent.removeChild(this);
  while (i--) { // i-- decrements i and returns the value of i before the decrement
    currentNode = arguments[i];
    if (typeof currentNode !== 'object'){
      currentNode = this.ownerDocument.createTextNode(currentNode);
    } else if (currentNode.parentNode){
      currentNode.parentNode.removeChild(currentNode);
    }
    // the value of "i" below is after the decrement
    if (!i) // if currentNode is the first argument (currentNode === arguments[0])
      parent.replaceChild(currentNode, this);
    else // if currentNode isn't the first
      parent.insertBefore(this.previousSibling, currentNode);
  }
}
if (!Element.prototype.replaceWith)
    Element.prototype.replaceWith = ReplaceWithPolyfill;
if (!CharacterData.prototype.replaceWith)
    CharacterData.prototype.replaceWith = ReplaceWithPolyfill;
if (!DocumentType.prototype.replaceWith) 
    DocumentType.prototype.replaceWith = ReplaceWithPolyfill;

Specification

Specification Status Comment
DOM
The definition of 'ChildNode.replacewith()' in that specification.
Living Standard Initial definition.

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Basic support 54 17 49 No 39 No
Mobile
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support 54 54 No 49 39 No 6.0

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith