Skip to content

Instantly share code, notes, and snippets.

@arv
Created October 6, 2011 21:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arv/1268805 to your computer and use it in GitHub Desktop.
Save arv/1268805 to your computer and use it in GitHub Desktop.
Node.prototype.append
(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());
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment