Skip to content

Instantly share code, notes, and snippets.

@jasondmoss
Last active December 10, 2019 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasondmoss/b6c00aa38be1a25f8e0a50c1f22d2d81 to your computer and use it in GitHub Desktop.
Save jasondmoss/b6c00aa38be1a25f8e0a50c1f22d2d81 to your computer and use it in GitHub Desktop.
Polyfill Methods for Internet Explorer 11 and below.
/**
* Polyfill for `ChildNode.replaceWith()`
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith
*/
function replaceWith()
{
"use-strict";
var parent = this.parentNode;
var i = arguments.length;
var currentNode;
if (!parent) {
return;
}
// If there are no arguments.
if (!i) {
parent.removeChild(this);
}
// i-- decrements i and returns the value of i before the decrement.
while (i--) {
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(currentNode, this.previousSibling);
}
}
}
if (!Element.prototype.replaceWith) {
Element.prototype.replaceWith = replaceWith;
}
if (!CharacterData.prototype.replaceWith) {
CharacterData.prototype.replaceWith = replaceWith;
}
if (!DocumentType.prototype.replaceWith) {
DocumentType.prototype.replaceWith = replaceWith;
}
/* <> */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment