Javascript-generated tables and rowspan

At work, I’ve recently been putting together a nice little calendar-like utility using Javascript. Basically, it has to generate a table consisting of cells which may span multiple rows. Surely the solution is simple enough: just set the rowspan on each td as we create it. Unfortunately, that doesn’t work, at least not in Firefox.

It appears that in Firefox, if you create a td and set its rowspan to some value when there are no rows for it to expand into, the attribute will be completely ignored, even if you add rows afterwards! Needless to say, this is very annoying. The solution? Build your table backwards.

The code I have now is something like this (note that I’m developing using the Mootools framework):

[sourcecode language=’javascript’]var tbl = new Element(‘table’);
var trs = [];

for (var i = 0; i < 4; i++) { var tr = new Element('tr'); tr.grab(new Element('td', { 'html': 'Cell ' + i })); if (i % 2 == 0) { tr.grab(new Element('td', { 'rowspan': 2, 'html': 'Span ' + (i / 2) })); } trs.push(tr); }for (var i = trs.length - 1; i >= 0; i–) {
tbl.grab(trs[i], ‘top’);
}[/sourcecode]

What does this code do? Well basically, we’re creating a table with ten rows and two columns; the cells in the right-hand column each occupy two rows. The result will be something like this:

Cell 1Span 1
Cell 2
Cell 3Span 2
Cell 4

Comments

3 responses to “Javascript-generated tables and rowspan”

  1. Sigilium Avatar
    Sigilium

    Hi, this hint ended my frustration due to this strange behavior. Thanks for saving me a lot of time to finally find this out by myself.

  2. Leonel Avatar
    Leonel

    Thanks!! So obvious after you see it!!!

  3. somayeh Avatar
    somayeh

    Thanks very much!! it is usful

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.