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
5 comments so far

Why not use Templates?

Regards,
Armin

Armin:
I have experimented with different ways of building HTML. For Skeletonz I have mostly used HTML templates. For Todoist I have mostly used JavaScript DOM.

The power of building HTML via JavaScript is that it's much easier to handle events, use JavaScript tricks or create generic template code. Using DOM is also a lot faster.

Amir,
did you have to change anything in your AJS in order for your last hack to work? Or are you using the exact code that you released in the 4.0 version?

thanks
Tim

It will be interesting to use something like that to:

var table = TABLE({'class': 'fluffy'},
                TBODY([ TR(), TR() ])
                );
);

Tim:
It's the same code. It's just the assignments that are pretty smart.

RStankov:
It's already possible to do this:

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

But a lot of times one would like to reference a TR element (for example to append children to it), that's where the assignments come into the picture ;)

Post a comment
Commenting on this post has expired.
© 2000-2009 amix. Powered by Skeletonz.