Created
November 26, 2010 17:32
-
-
Save silentmatt/716987 to your computer and use it in GitHub Desktop.
Makes a DOM tree from JavaScript "S-expressions"
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
var make = (function() { | |
if (typeof Array.isArray !== 'function') { | |
Array.isArray = function(a) { | |
return Object.prototype.toString.call(a) === "[object Array]"; | |
}; | |
} | |
function make(desc) { | |
if (!Array.isArray(desc)) { | |
return make.call(this, Array.prototype.slice.call(arguments)); | |
} | |
var name = desc[0]; | |
name = splitTag(name); | |
var attrs = name[1]; | |
name = name[0]; | |
var attributes = desc[1]; | |
var el = document.createElement(name); | |
var start = 1; | |
if (typeof attributes === "object" && attributes !== null && !Array.isArray(attributes)) { | |
mergeAttributes(attrs, attributes); | |
start = 2; | |
} | |
attributes = attrs; | |
for (var attr in attributes) { | |
if (typeof attributes[attr] === 'string') { | |
console.log(attr, attributes[attr]); | |
el.setAttribute(attr, attributes[attr]); | |
} | |
else { | |
el[attr] = attributes[attr]; | |
} | |
} | |
for (var i = start; i < desc.length; i++) { | |
if (Array.isArray(desc[i])) { | |
el.appendChild(make(desc[i])); | |
} | |
else if (desc[i] instanceof Element) { | |
el.appendChild(desc[i]); | |
} | |
else { | |
el.appendChild(document.createTextNode(desc[i])); | |
} | |
} | |
return el; | |
} | |
function mergeAttributes(attr1, attr2) { | |
for (var key in attr2) { | |
if (!attr1.hasOwnProperty(key)) { | |
attr1[key] = attr2[key]; | |
} else if (key === "class") { | |
attr1[key] += " " + attr2[key]; | |
} | |
} | |
} | |
function splitTag(tag) { | |
var attr = {}; | |
var c = tag.split("."); | |
var t = c[0].split("#"); | |
if (t[1]) attr.id = t[1]; | |
if (c.length > 1) attr["class"] = c.slice(1).join(" "); | |
return [t[0] || "div", attr]; | |
} | |
return make; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment