As someone said somewhere: 'I’d rather save myself the time of having to code 20 lines of createElement/appendChild’s when a single innerHTML will suffice'.
It's perfectly simple to write a helper function that makes using the DOM a lot more fun. I usually use something simple and lightweight like:
Code:
function map(f, arr) {
for(var i = 0, r = []; i < arr.length; r[i] = f(arr[i++]));
return r;
}
var jsonToDom = (function() {
var TAG = 0, ATTRS = 1, CHILDREN = 2;
function addTo(parent) {
return function(x) {
return parent.appendChild(jsonToDom(x));
};
}
function jsonToDom(o) {
if(typeof o === "string")
return document.createTextNode(o);
var r;
if(o[TAG] instanceof Array) {
r = document.createDocumentFragment();
map(addTo(r), o);
} else {
r = document.createElement(o[TAG]);
for(var x in o[ATTRS])
if(o.hasOwnProperty(x))
r[x] = o[x];
map(addTo(r), o[CHILDREN]);
}
return r;
}
return jsonToDom;
})();
... but if you wanted to be really interoperable, you could use JsonML, which has a sample converter for DOM.
That being said, I admit that innerHTML is not part of the W3C DOM. But what about Ajax?
AJAX is a methodology, not a technology, and thus does not require a standard. The technology that makes it possible, the XMLHttpRequest object, is being standardised as I type.
Edit: Use for jsonToDom():
Code:
myElement.innerHTML += "<p class=\"foo\" name=\"bar\" style=\"baz\"><span id="quux" onclick=\"alert("Hi!");\">Quuux</span>Quuuux</p>";
// becomes:
myElement.appendChild(jsonToDom(["p",
{className: "foo",
name: "bar",
cssString: "baz"},
[["span",
{id: "quux",
onclick: function(e) { alert("Hi!"); }},
["Quuux"]],
"Quuuux"]));
// or, if you've been using innerHTML so long you hate actual code formatting,
myElement.appendChild(jsonToDom(["p", {className: "foo", name: "bar", cssString: "baz"}, [["span", {id: "quux", onclick: function(e) { alert("Hi!"); }}, ["Quuux"]], "Quuuux"]));
Slightly more verbose, but much easier to format, no ugly quote escapes, and doesn't erase and recreate every other child in myElement.
Bookmarks