json2dom
Saturday, February 11th, 2006 at 12:00 pm
Download the .js file (3.7 KB)
The json2dom function will create HTML nodes from a JSON object that defines their properties. The object should be an array of objects, each of which represents a single HTML element. For most elements, the tag property should be used to define what type of HTML element it represents, such as div, ul, hr, and so forth. Alternatively, a text property can be set to represent a text node.
Another property, properties, should be set with any attributes for the element, such as className or id. Any HTML element that supports children can have a children property, an array of objects that will be appended the the parent.
This will probably make more sense once you see it. The following JSON object could be run through the function:
[
{"tag":"div","properties":{"id":"textBox"}, "children":
[
{"tag":"input","properties":{"type":"text"}},
{"tag":"br"},
{"text":"Some text to mix it up"},
{"tag":"br"},
{"tag":"input","properties":{"type":"text"]}
]
},
{"text":"This is some text!"},
{"tag":"hr"}
]
This would be evaluated as a div containing an input box, a break line, a line of text, another break line, and another input box. After the div comes another line of text, and then a horizontal line. All top-level elements are returned by the function in an array - in this case, the div, line of text (”This is some text!”), and horizontal line would be in the array.
I really don’t know if there’s any practical use for this, but it kept me busy on a Saturday afternoon. The example here uses appendChildren() from Prototype Plus, which I haven’t really documented yet. I also used JSON-PHP to generate the JSON object, since it’s a lot easier to build a readable associative array in PHP than in JavaScript.
Feel free to e-mail me with any suggestions or bugs.
Click here to execute the code above.