16Jul/104
JSONimal – Elegant DOM Contruction with jQuery
Occasionally for Javascript projects, I found myself building a lot of HTML programatically, and I wasn't satisfied with any of the techniques available, so I built JSONimal. I was originally going to just call it JSONML, but that was taken.
What's it do? This example should demonstrate my goal fairly well.
$(function() {
$.mktag("#demo").jsonimal([
["h1", {text: "JSONimal!"}],
["table",{style: 'border: 1px solid black'},[
["thead",[
["tr",{style: 'text-transform: uppercase'},[
["th", {text: "one"}],
["th", {text: "two"}],
["th", {text: "three"}]
]]
]],
["tbody", [
["tr",[
["td", {html: "<u>a</u>"}],
["td", {text: "b"}],
["td", {text: "c"}]
]],
["tr",[
["td",[
["a", {href: "http://www.google.ca", text: "Google"}]
]],
["td", {text: "b"}],
["td", {text: "c"}]
]],
["tr",[
["td", {text: "a"}],
["td", {text: "b"}],
["td", {text: "c"}]
]]
]]
]]
]).appendTo("body");
});
Which will add this to the body:
JSONimal!
| one | two | three |
|---|---|---|
| a | b | c |
| b | c | |
| a | b | c |
For more information and examples, check out the github page: JSONimal @ github.
I also posted it as on the jQuery plugins page - but that just points to the github page anyway. JSONimal @ plugins.jquery.com
July 16th, 2010 - 16:10
This is a really excellent idea! I have the same issue with generating HTML programmatically with JavaScript, it’s always a lot more awkward than it should be, especially with longer blocks of code and where setting a lot of attributes is necessary. Good work!
July 16th, 2010 - 17:02
The name JsonML was taken because it does the exact same thing. You should check it out because it is a pretty mature product.
July 17th, 2010 - 09:46
Reusing a well-maintained existing project is always a Good Idea. JsonML, Google Web Toolkit, XSLT + CSS could all have done similar tasks.
Go learn one of ‘em?
July 17th, 2010 - 13:15
They all could have done similar things, but missing a few things.
JsonML, while being a much more mature, extensive product, lacks the hamlesque syntax of doing something like “span#testid.c1.c2.c3″, which can be very helpful when generating javascript with CSS being applied to it.
I know that it has the ability to assign classes and ID’s through the {id: ‘testid’, class: ‘c1 c2 c3′} system, but the difference in that syntax is substantial for me.
And in any case, I agree that reusing well maintained existing products is a good idea for being products where perfect stability is an issue, but it also isn’t remotely as useful an exercise in learning.