Last active
January 22, 2020 16:50
-
-
Save ivandoroshenko/33e9a90d14f9f573cf387f3296b97c40 to your computer and use it in GitHub Desktop.
ChildNode.append() polyfill
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
/** | |
* ChildNode.append() polyfill | |
* https://gomakethings.com/adding-an-element-to-the-end-of-a-set-of-elements-with-vanilla-javascript/ | |
* @author Chris Ferdinandi | |
* @license MIT | |
*/ | |
(function (elem) { | |
// Check if element is a node | |
// https://github.com/Financial-Times/polyfill-service | |
var isNode = function (object) { | |
// DOM, Level2 | |
if (typeof Node === 'function') { | |
return object instanceof Node; | |
} | |
// Older browsers, check if it looks like a Node instance) | |
return object && | |
typeof object === "object" && | |
object.nodeName && | |
object.nodeType >= 1 && | |
object.nodeType <= 12; | |
}; | |
// Add append() method to prototype | |
for (var i = 0; i < elem.length; i++) { | |
if (!window[elem[i]] || 'append' in window[elem[i]].prototype) continue; | |
window[elem[i]].prototype.append = function () { | |
var argArr = Array.prototype.slice.call(arguments); | |
var docFrag = document.createDocumentFragment(); | |
for (var n = 0; n < argArr.length; n++) { | |
docFrag.appendChild(isNode(argArr[n]) ? argArr[n] : document.createTextNode(String(argArr[n]))); | |
} | |
this.appendChild(docFrag); | |
}; | |
} | |
})(['Element', 'CharacterData', 'DocumentType']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment