Using JSON to create your DOM elements
While working on a webapplication using AJAX technology I found myself reading XML and writing that to the DOM; but doing that is really frustrating. Check out this hideous piece of code I needed to create a simple element:
var dom_item_date, dom_item_title_text, dom_item_title_link;
var dom_item_content_text, dom_item_title, dom_feed_item;
dom_item_date = document.createElement('dt');
dom_item_date.appendChild(document.createTextNode(item.getFirstValue('pubDate')));
dom_item_title_text = document.createTextNode(item.getFirstValue('title'));
dom_item_title_link = document.createElement('a');
dom_item_title_link.href = item.getFirstValue('link');
dom_item_title_link.appendChild(dom_item_title_text);
dom_item_content_text = document.createTextNode(item.getFirstValue('description'));
dom_item_content = document.createElement('p');
dom_item_content.appendChild(dom_item_content_text);
dom_item_title = document.createElement('dd');
dom_item_title.appendChild(dom_item_title_link);
dom_feed_item.appendChild(dom_item_date);
dom_feed_item.appendChild(dom_item_title);
dom_feed_item.appendChild(dom_item_content);
So I wanted a different setup. Reading about JSON I assumed there was an easy way to put JSON object in the DOM. The only one I found is this script. However; the example still seems a bit too long, with redundunt stuff in it. So I decided to create an alternative. Check this out:
var feed_item = {
dt : {
_text : item.getFirstValue('pubDate')
},
dd : {
a : {
href : item.getFirstValue('link'),
_text : item.getFirstValue('title')
}
},
p : {
_text : item.getFirstValue('description')
}
}
var dom_feed_item = Object2DOM(feed_item);
Can you believe that this easy-readable script does the exact same thing that the first script did? This is really going to add joy to my Javascript-DOM coding! You can download the Object2DOM script here. Everything should be quite intuive; the only thing special is that you need to name your attribute ‘_text’ if you want a textnode to be created. Also; since the Object specification requires you to have a top-level element to hold all the sub-items; I am currently converting this top-level element to a <span>, but this can be changed easily inside the script.