Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active September 15, 2020 14:41
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 tomhodgins/14451f123e1878e766c9568ecce13878 to your computer and use it in GitHub Desktop.
Save tomhodgins/14451f123e1878e766c9568ecce13878 to your computer and use it in GitHub Desktop.
A polyfill for parentNode.replaceChildren()
// Polyfill for parentNode.replaceChildren()
// Spec: https://dom.spec.whatwg.org/#dom-parentnode-replacechildren
// Docs: https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/replaceChildren
// Gecko implementation: https://github.com/mozilla/gecko-dev/blob/master/dom/base/nsINode.cpp#L2027
// Webkit implementation: https://github.com/WebKit/webkit/blob/master/Source/WebCore/dom/ContainerNode.cpp#L958
// Source: https://gist.github.com/tomhodgins/14451f123e1878e766c9568ecce13878
if (typeof Element.prototype.replaceChildren !== 'function') {
Object.defineProperty(Element.prototype, 'replaceChildren', {
configurable: true,
writable: true,
value: function replaceChildren(...nodes) {
// Remove all existing child nodes
while (this.firstChild) {
this.removeChild(this.firstChild)
}
// Append new DOM objects
this.append(...nodes)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment