John: you can see here that you have a pattern: create link, add href, add text, append link; and also that you have some code that's basically non-flat but that has had to be flattened, harming readability. A good thing to do in these situations is to abstract out:
Code:
<div id="val_$_val"></div>
<script type="text/javascript">
Function.id = function(a) { return a; };
Array.map = function(f, a) {
for (var i = 0, r = []; i < a.length; ++i)
r[i] = f(a[i]);
return r;
};
Array.intersperse = function(el, a) {
if (a.length < 2)
return a;
for (var i = 1, r = [a[0]]; i < a.length; ++i)
r.push(el, a[i]);
return r;
};
var Dom = (function() {
function get(a) {
return document.getElementById(a);
}
var attrmap = {
class: "className"
// &c.
};
function applyAttributes(el, attrs) {
for (var x in attrs)
if (attrs.hasOwnProperty(x))
if (x === "style")
el.setAttribute("style", el.style.cssText = attrs[x]);
else
el[attrmap[x] || x] = attrs[x];
return el;
}
function addChildren(el, children, filter) {
Array.map(function(child) {
if (!child) return;
if (child = create(child))
el.appendChild(child);
}, children);
}
function create(el, filter) {
if (typeof el === "string")
return document.createTextNode(el);
if (!(el instanceof Array))
return el;
filter = filter || Function.id;
var r = document.createElement(el[0]),
attrs = el[1],
children = el[2];
applyAttributes(r, attrs);
addChildren(r, children, filter);
return filter(r);
}
function link(contents, href, title) {
return ["a", {href: href, title: title}, [contents]];
}
return {
create: create,
get: get,
link: link
};
})();
// Elements are expressed as an array of three elements:
// [tagName : string, attributes : Object, children : Array]
Dom.get("val_$_val").appendChild(Dom.create(
["p", {}, Array.intersperse(" | ",
[Dom.link("Privacy Policy"),
Dom.link("Terms of Use"),
Dom.link("Disclaimer"),
Dom.link("XHTML",
"http://validator.w3.org/check/referer",
"This page validates as XHTML 1.0 Transitional"),
Dom.link("CSS",
"http://jigsaw.w3.org/css-validator/check/referer",
"This page validates as CSS 2")]
]));
</script>
As you can see, this greatly improves legibility and removes redundancy from the code.
Untested, weird bugs may exist.
Bookmarks