まえのとあわせて

$N = function (name, attr, childs) {
var ret = document.createElement(name);
for (k in attr) {
if (!attr.hasOwnProperty(k)) continue;
v = attr[k];
if (k == "class") {
ret.className = v;
} else {
ret.setAttribute(k, v);
}
}
switch (typeof childs) {
case "string": {
ret.appendChild(document.createTextNode(childs));
break;
}
case "object": {
for (var i = 0, len = childs.length; i < len; i++) {
var child = childs[i];
if (typeof child == "string") {
ret.appendChild(document.createTextNode(child));
} else {
ret.appendChild(child);
}
}
break;
}
}
return ret;
}
var pq;
document.body.appendChild($N("div", {}, [
$N("div", {style:"font-weight:bold"}, "foobar"),
$N("div", {}, [
pq = $N("ol")
])
]));
for (var i = 0; i < 10; i++)
pq.appendChild($N("li", {}, "hoge");
var div = $N("div");

みたいなのを使ってる。

innerHTML を使いたくない (application/xhtml+xml では一切使えない) けど、document.createElement の嵐はキモイ。中間とって GreaseMonkey のテンプレート (xyzzy の拡張 lisp を入れてる) にごちゃごちゃ書いてしのいでるます。

  1. トップ
  2. js
  3. 簡易ビルダー
▲ この日のエントリ