Last active
August 29, 2015 14:15
-
-
Save DigiTec/7db2c77bd66d0222bb8b to your computer and use it in GitHub Desktop.
Duck Typing Demos for Array -> HTMLCollection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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