The right way to create DOM on the fly with jQuery
19 Mar 2010I was reviewing the source code of a project when I realized that it was painful to create DOM on the fly while retaining the human-readable syntax. However, it is now improved thanks to the new API from jQuery 1.4
In my simple example, I was trying to create a dynamic table row and add it to a table. The ultimate goal is to create those HTML elements
[sourcecode language="html"]
<table>
<tr>
<td>foobar</td>
<td>
<input type="text" value="foobar" name="rule[properties][foobar]">
</td>
<td>
<input type="checkbox" value="1" name="rule[important][foobar]">
</td>
<td style="text-align: right;">
<img title="remove" alt="remove" src="/buttons/pane_button_remove.png">
</td>
</tr>
</table>
[/sourcecode]
The old code was:
[sourcecode language="javascript"]
var row = jQuery("<tr />")
.appendTo("table");
jQuery("<td />")
.text(name)
.appendTo(row);
var valueCell = jQuery("<td />")
.appendTo(row);
jQuery("<input />")
.attr({
type: "text",
name: "rule[properties][" + name + "]"
})
.val(value)
.appendTo(valueCell);
jQuery("<img />")
.attr({
src: "button_close.png",
alt: "remove"
})
.click(function(e) {
jQuery(this).closest("tr").remove();
})
.appendTo(valueCell);
[/sourcecode]
I bet the above code is too long and messy that you almost dont want to read it, right? How about the below one?
[sourcecode language="javascript"]
jQuery("<tr />")
.append(
jQuery("<td />", {
text: name
})
)
.append(
jQuery("<td />", {
html: jQuery("<input />", {
"type": "text",
"name": "rule[properties][" + name + "]",
val: value
})
})
)
.append(
jQuery("<td />", {
html: jQuery("<input />", {
"type": "checkbox",
"name": "rule[important][" + name + "]",
"checked": isImportant
})
})
)
.append(
jQuery("<td />", {
"style": "text-align: right;",
html: jQuery("<img />", {
"src": "/buttons/pane_button_remove.png",
click: function() { jQuery(this).closest("tr").remove(); }
})
})
)
.appendTo("table");
[/sourcecode]
The two approach of creating DOM on the fly produce the same HTML code to the document. However, the second one seems to be more human-readable. It also mimics the semantic syntax of HTML so it is much easier to maintain thanks to the new API in jQuery 1.4
Do you have any better idea about creating DOM without using a plugin? Share it with me.