While I was porting the Lightbox library to a Mandoo module, I saw the way that Prototype handles elements creation and remembered the jQuery "different" – dirty, actually – way. I tweeted about it and got some replies from others JavaScript developers, dirs and gabrielgilini. This post will show the three different ways these libraries offer to create DOM elements trees. First, the jQuery way:
$('#grid').append(
'<tr class="even">' +
'<td width="250">' +
'<input type="checkbox" id="check"/>' +
'<input type="text" id="item"/>' +
'</td>' +
'<td>' +
'<a class="link" href="#" title="delete this item">Delete</a>' +
'</td>' +
'</tr>'
);
Well, personally I really don’t like to mess HTML code with my JavaScript stuff (I am almost sure that neither you do). Thinking this way, we have another option, with Prototype:
$$('#grid')[0].appendChild(Builder.node('tr', {className:'even'}, [
Builder.node('td', {width:'250'}, [
Builder.node('input', {type:'checkbox',id:'check'}),
Builder.node('input', {type:'type',id:'item'})
]),
Builder.node('td', [
Builder.node('a', {href:'#',title:'delete this item'}, 'Delete')
])
]));
Better, but we want something cleaner, simpler. What about joining the best ideas? The Mandoo way, using CSS selectors to create elements (why not?
):
u('#grid').append('tr.even')
.append('td[width=250]')
.add('input#check[type="checkbox"]')
.add('input#item[type="text"]')
.up()
.append('td')
.add('a.link[href="#"][title="delete this item"]', 'Delete');
Mandoo helps you to keep things simple, organize your code and follow the best JS coding practices. Share your thoughts and happy coding!


