Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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