Created
April 6, 2016 23:51
-
-
Save jongacnik/65c0ae073500ecc014177f37d7175e8a to your computer and use it in GitHub Desktop.
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
function normalise(nodes) { | |
return nodes.reduce(function(rv, e) { | |
return rv.concat(Array.isArray(e) | |
? normalise(e) | |
: e.nodeType | |
? [e] | |
: [document.createTextNode(e)]); | |
}, []); | |
} | |
function createNode(tag, attrs, children) { | |
var node = document.createElement(tag); | |
normalise(children).forEach(node.appendChild.bind(node)); | |
for (var i in attrs) | |
node.setAttribute(i, attrs[i]); | |
return node; | |
} | |
var type = {}.toString; | |
var kr = function (tag, attrs, children) { | |
if (attrs && type.call(attrs) !== '[object Object]') { | |
children = attrs; | |
attrs = {}; | |
} | |
return createNode(tag, attrs, children | |
? Array.isArray(children) | |
? children | |
: [children] | |
: []); | |
} | |
kr.addTag = function(tag) { | |
kr[tag] = function(attrs, children) { | |
return kr(tag, attrs, children); | |
}; | |
}; | |
// set up default elements | |
[ | |
'h1', 'h2', 'h3', 'h4', | |
'div', 'span', 'p', 'style', 'article', 'aside', | |
'figure', 'figcaption', | |
'a', 'ul', 'ol', 'li', | |
'table', 'tr', 'th', 'td', | |
'b', 'i', 'u', | |
'hr', 'br', 'sub', 'sup', | |
'input', 'button', | |
].forEach(kr.addTag); | |
module.exports = kr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment