DOM enlightenment (JS trick)

Standard DOM sucks because it hides the real structure of some HTML. In this post I present a new way of building DOM that preserves the structure of HTML and makes it much more readable.

The standard way of using DOM

var table = document.createElement('table');
table.className = 'fluffy';
var tbody = document.createElement('tbody');
var tr_1 = document.createElement('tr');
var tr_2 = document.createElement('tr');
table.appendChild(tbody);
tbody.appendChild(tr_1);
tbody.appendChild(tr_2);

Urghggh.

Using AJS DOM

var table = TABLE({'class': 'fluffy'});
var tbody = TBODY();
var tr_1 = TR();
var tr_2 = TR();
ACN(table, tbody);
ACN(tbody, tr_1); 
ACN(tbody, tr_2);

Still not that readable, since the code does not follow the structure of HTML.

AJS DOM + a hack

var tbody, tr_1, tr_2;
var table = TABLE({'class': 'fluffy'},
    tbody = TBODY(
        tr_1 = TR(),
        tr_2 = TR()
    )
);

Just compare this to the other examples...!

Related

Code · Code improvement · JavaScript · Tips 15. Jun 2007
© Amir Salihefendic. Powered by Skeletonz.