開示: 私は BOB のメンテナーです。
このプロセスをはるかに簡単にするBOBと呼ばれる JavaScript ライブラリがあります。
あなたの特定の例について:
<div><img src="the url" />the name</div>
これは、次のコードによって BOB で生成できます。
new BOB("div").insert("img",{"src":"the url"}).up().content("the name").toString()
//=> "<div><img src="the url" />the name</div>"
または短い構文で
new BOB("div").i("img",{"src":"the url"}).up().co("the name").s()
//=> "<div><img src="the url" />the name</div>"
このライブラリは非常に強力で、データ挿入 (d3 と同様) を使用して非常に複雑な構造を作成するために使用できます。
data = [1,2,3,4,5,6,7]
new BOB("div").i("ul#count").do(data).i("li.number").co(BOB.d).up().up().a("a",{"href": "www.google.com"}).s()
//=> "<div><ul id="count"><li class="number">1</li><li class="number">2</li><li class="number">3</li><li class="number">4</li><li class="number">5</li><li class="number">6</li><li class="number">7</li></ul></div><a href="www.google.com"></a>"
BOB は現在、DOM へのデータの挿入をサポートしていません。これは todolist にあります。今のところ、出力を通常の JS または jQuery と一緒に使用して、好きな場所に置くことができます。
document.getElementById("parent").innerHTML = new BOB("div").insert("img",{"src":"the url"}).up().content("the name").s();
//Or jquery:
$("#parent").append(new BOB("div").insert("img",{"src":"the url"}).up().content("the name").s());
このライブラリを作成したのは、jquery や d3 などの代替手段に満足できなかったからです。コードが非常に複雑で読みにくい。私の意見では、BOB と一緒に仕事をするのは明らかに偏っていますが、ずっと楽しいものです。
BOB はBowerで利用できるので、 を実行して取得できますbower install BOB
。