Quicktags
Laziness being the mother of all inventions, I created a function in javascript which'd help me create DOM nodes quickly, here's the source:
/**
* Shortcut for creating a new html tag using JSON notation.
* @param JSON The tag using JSON notation. The first value of the object
* is the tag name, second child is array of parameters and third child
* is array of children elements. If the first parameter is a string, the
* node is assumed to be a text node and has no further children.
*/
function quickTag(JSON){
var elem;
if(typeof(JSON) == 'string'){
elem = document.createTextNode(JSON);
} else {
// Create the element itself
elem = document.createElement(JSON[0]);
// Add attributes
if(JSON[1])
for( attr in JSON[1] ){
elem.setAttribute(attr, JSON[1][attr]);
}
// Add child elements
if(JSON[2])
for(var j=0;j<JSON[2].length;j++){
elem.appendChild( quickTag(JSON[2][j]) );
}
}
return elem;
}
Download source
Here's a quick example of the usage, hopefully you'll see what the syntax is fairly quickly. Note that the parameter uses JSON syntax, you might want to quickly read up on that if you're not too familiar with it. It's very simple and would only take a few minutes.
var p = quickTag(['p',{'class':'test'},["This is a ",['em',,'test']," node."]]);
document.body.appendChild( p );
The first item in the array is the tag name, the second is attributes and their values given as an object and the third parameter is child elements, which means that you can start all over again with a new array, or just pass a string to use as a text node. The above example would produce the output equivalent to
<p class="test">This is a <em>test</em> node.</p>
It has been tested and works with Opera 9 and Firefox 1.5.0.4, I don't have other browsers to test with right here right now, but I suspect Internet Explorer will throw a fit if trying to set class by setAttribute. It's always a hoot with that old thing...