Skip to content

Instantly share code, notes, and snippets.

@abbotto
Last active April 27, 2018 08:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abbotto/d5b7461cd0d90e2ec7ec to your computer and use it in GitHub Desktop.
Save abbotto/d5b7461cd0d90e2ec7ec to your computer and use it in GitHub Desktop.
polyfill.insertAdjacentHTML.js
/*!
* polyfill.insertAdjacentHTML.js
* Author: Jared Abbott
* Description: A Cross-browser implementation of HTMLElement.insertAdjacentHTML
* Copyright 2015 Jared Abbott
* Distributed under the MIT license
*/
if (!("insertAdjacentHTML" in document.createElementNS("http://www.w3.org/1999/xhtml", "_"))) {
HTMLElement.prototype.insertAdjacentHTML = function(position, html) {
"use strict";
var node,
element = this,
container = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "_"),
parent = element.parentNode,
nodeFrag = document.createDocumentFragment();
// Make position lowercase
position = position.toLowerCase();
// Insert the container HTML and append the resulting nodes to nodeFrag
container.innerHTML = html;
while (node == container.firstChild){
nodeFrag.appendChild(node);
}
// Add nodes to DOM
if (position === "beforeend") {
element.appendChild(nodeFrag);
} else if (position === "afterbegin") {
element.insertBefore(nodeFrag, element.firstChild);
} else if (position === "beforebegin") {
parent.insertBefore(nodeFrag, element);
} else if (position === "afterend") {
parent.insertBefore(nodeFrag, element.nextElementSibling);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment