Skip to content

Instantly share code, notes, and snippets.

@kafene
Last active August 29, 2015 14:18
Show Gist options
  • Save kafene/8e56adaf3c1ca4188938 to your computer and use it in GitHub Desktop.
Save kafene/8e56adaf3c1ca4188938 to your computer and use it in GitHub Desktop.
Element.prototype.insertAdjacentElement shim

This is a shim for Element.prototype.insertAdjacentElement, which is supported all major browsers except Firefox.

Example: https://jsfiddle.net/kafene/s6Lweg5k/

if ("undefined" === typeof (Element.prototype.insertAdjacentElement)) {
    Object.defineProperty(Element.prototype, "insertAdjacentElement", {
        enumerable: false,
        writable: true,
        configurable: true,
        value: function (position, elem) {
            switch (position.toString().toUpperCase()) {
                case "BEFOREBEGIN":
                    return this.parentNode.insertBefore(elem, this);
                case "AFTERBEGIN":
                    return this.insertBefore(elem, this.firstChild);
                case "BEFOREEND":
                    return this.appendChild(elem);
                case "AFTEREND":
                    return this.parentNode.insertBefore(elem, this.nextSibling);
                default:
                    throw new Error("Invalid element position `" + position + "`");
            }
        }
    });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment