Skip to content

Instantly share code, notes, and snippets.

@DigiTec
Last active August 29, 2015 14:15
Show Gist options
  • Save DigiTec/7db2c77bd66d0222bb8b to your computer and use it in GitHub Desktop.
Save DigiTec/7db2c77bd66d0222bb8b to your computer and use it in GitHub Desktop.
Duck Typing Demos for Array -> HTMLCollection
// http://jsfiddle.net/w3mw1r4q/
var ary = Array.apply(null, document.body.children);
console.log(Array.isArray(document.body.children));
console.log(Array.isArray(ary));
console.log(ary.length);
// http://jsfiddle.net/61qsygbg/
var circ = document.createElementNS("http://www.w3.org/2000/svg", "circle");
console.log(circ.toString());
// Let's set some class
circ.setAttribute("class", "foo bar baz");
// Try to get and use classList
console.log(circ.classList);
// Move the classList down the prototype chain
Object.defineProperty(Element.prototype, "classList", Object.getOwnPropertyDescriptor(HTMLElement.prototype, "classList"));
// Try to get the classList now! Returns DOMTokenList with length 3
console.log(circ.classList);
// http://jsfiddle.net/Luozafh6/
var coll = document.getElementsByTagName("div");
// Simple one-time redirection
Array.prototype.forEach.call(coll, function (elem) {
console.log(elem.id);
});
Array.prototype.forEach.apply(coll, [function (elem) {
console.log(elem.id);
}]);
Array.prototype.forEach.bind(coll)(function (elem) {
console.log(elem.id);
});
// Apply to all HTMLCollection objects by extending the prototype
HTMLCollection.prototype.forEach = Array.prototype.forEach;
coll.forEach(function (elem) {
console.log(elem.id);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment