Skip to content

Instantly share code, notes, and snippets.

@Skateside
Created February 8, 2018 19:59
Show Gist options
  • Save Skateside/a64202dc1911a252968f09838f8200b5 to your computer and use it in GitHub Desktop.
Save Skateside/a64202dc1911a252968f09838f8200b5 to your computer and use it in GitHub Desktop.
A simple polyfill for the "jQuery style methods" that have been added recently. Written in ES6 syntax
function polyfill(object, name, value) {
if (typeof object[name] !== typeof value) {
Object.defineProperty(object, name, {
value,
configurable: true,
enumerable: false,
writable: true
});
}
}
function polfillAll(objects, methods) {
if (!Array.isArray(objects)) {
objects = [objects];
}
objects.forEach((object) => {
Object
.entries(methods)
.forEach(([key, value]) => polyfill(object, key, value));
});
}
polyfill(
Object,
"entries",
(object) => Object.keys(object).map((key) => [key, object[key]])
);
let addToFrag = (...args) => {
let frag = document.createDocumentFragment();
args.forEach((arg) => {
frag.appendChild(
arg instanceof Node
? arg
: document.createTextNode(String(arg))
);
});
return frag;
};
polyfillAll(
[
Element.prototype,
Document.prototype,
DocumentFragment.prototype
],
{
append(...args) {
this.appendChild(addToFrag(...args));
}
prepend(...args) {
this.insertBefore(addToFrag(...args), this.firstChild);
}
}
);
polyfill(Element.prototype, "closest", (selector) => {
let element = this;
let closest = null;
if (document.documentElement.contains(element)) {
do {
if (element.matches(selector)) {
closest = element;
break;
}
element = element.parentElement || element.parentNode;
} while (element !== null);
}
return closest;
});
polyfillAll(
[
Element.prototype,
CharacterData.prototype,
DocumentType.prototype
]
{
before(...args) {
this.parentNode.insertBefore(addToFrag(...args), this);
}
after(...args) {
this.parentNode.insertBefore(addToFrag(...args), this.nextSibling);
}
remove() {
if (this.parentNode) {
this.parentNode.removeChild(this);
}
}
replaceWith(...args) {
// I only THINK this is a complete polyfill. Kinda hard to follow
// the MDN example.
this.before(...args);
this.remove();
}
}
);
// NodeList.prototype.forEach.length = 1
polyfill(NodeList.prototype, "forEach", (...args) => {
Array.prototype.forEach.apply(this, args);
});
@james-jlo-long
Copy link

The polyfillAll methods (before, replaceWith etc.) should have a length of 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment