Skip to content

Instantly share code, notes, and snippets.

@MatrixFrog
Created February 18, 2012 07:01
Show Gist options
  • Save MatrixFrog/1857944 to your computer and use it in GitHub Desktop.
Save MatrixFrog/1857944 to your computer and use it in GitHub Desktop.
DOM Builder
<script src="DOMBuilder.js"></script>
<script>
domBuilder(
[/HTML/],
[/HEAD/],
[/TITLE/],
"Wouldn't this be cool?",
[],
[],
[/BODY/],
[/DIV/, {id: "container"}],
"Hello, world",
[],
[],
[]
);
</script>
// 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