public
Last active

Node.prototype.append

  • Download Gist
node-append.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
(function() {
 
function isNode(value) {
return value instanceof Node;
}
 
function isAttrObject(value) {
return value != null && typeof value === 'object' && !isNode(value);
}
 
function setAttributes(element, object) {
Object.keys(object).forEach(function(key) {
element.setAttribute(key, object[key]);
});
}
 
function toNode(value, doc) {
switch (typeof value) {
case 'boolean':
case 'number':
case 'string':
return doc.createTextNode(value.toString());
case 'undefined':
return doc.createTextNode('undefined');
default:
if (value === null) {
return doc.createTextNode('null');
}
if (isNode(value)) {
return value;
}
if (Array.isArray(value) && value.length >= 1) {
var element = doc.createElement(value[0]);
var i = 1;
 
if (value.length > i) {
if (isAttrObject(value[i])) {
setAttributes(element, value[i]);
i++;
}
 
if (value.length > i) {
element.append.apply(element, value.slice(i));
}
}
 
return element;
}
 
throw new Error();
}
}
 
Node.prototype.append = function() {
for (var i = 0; i < arguments.length; i++) {
this.appendChild(toNode(arguments[i], this.ownerDocument));
}
};
 
})();
 
 
/*
 
document.body.append('Hello', 'World');
document.body.append(['p', 'text', ['button', {style: 'color:red'}, 'Click me']]);
document.body.append(true, false, 1, 42, undefined, null, 'some', new Image());
 
*/

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.