Created
February 18, 2012 07:01
-
-
Save MatrixFrog/1857944 to your computer and use it in GitHub Desktop.
DOM Builder
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
<script src="DOMBuilder.js"></script> | |
<script> | |
domBuilder( | |
[/HTML/], | |
[/HEAD/], | |
[/TITLE/], | |
"Wouldn't this be cool?", | |
[], | |
[], | |
[/BODY/], | |
[/DIV/, {id: "container"}], | |
"Hello, world", | |
[], | |
[], | |
[] | |
); | |
</script> |
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
// https://github.com/jed/140bytes/wiki/Wishlist | |
function domBuilder() { | |
var elem, stack = [document.documentElement]; | |
[].forEach.call(arguments, function(arg, index) { | |
if (typeof arg == 'string') { | |
last(stack).appendChild(document.createTextNode(arg)); | |
} else if (!arg.length) { | |
elem = stack.pop(); | |
last(stack).appendChild(elem); | |
} else { | |
stack.push(makeElem(arg)); | |
} | |
}); | |
} | |
function makeElem(a) { | |
var name = a[0].toString().replace(/\//g, ''); | |
var elem = document.createElement(name); | |
if (a[1]) { | |
for (var attr in a[1]) { | |
elem.setAttribute(attr, a[1][attr]); | |
} | |
} | |
return elem; | |
} | |
function last(a) { | |
return a[a.length-1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment