Re: Simplifying element creation

I've started playing with create/append and they seem to work pretty well.

It simplified
    var table = document.createElement('table');
    table.appendChild(document.createElement('tbody'));
...
    for (var i = 0; i < labels.length; i++) {
        var tableRow = document.createElement('tr');
        var titleCell = document.createElement('td');
        titleCell.appendChild(document.createTextNode(labels[i]));
        tableRow.appendChild(titleCell);

        var valueCell = document.createElement('td');
        var bar = document.createElement('span');
        bar.className = 'bar';
        bar.style.width = <some expression> + '%';
        valueCell.appendChild(bar);

        var valueContainer = document.createElement('span');
        valueContainer.appendChild(document.createTextNode(values[i]));
        valueContainer.className = 'value-container';
        valueCell.appendChild(valueContainer);
        tableRow.appendChild(valueCell);
        table.childNodes[0].appendChild(tableRow);
    }
    element.appendChild(table);
to
    var table = Element.create('table', {}, [Element.create('tbody')]);
...
    for (var i = 0; i < labels.length; i++) {
        table.childNodes[0].append(
            Element.create('tr', {}, [
                Element.create('td', {}, [labels[i]]),
                Element.create('td', {}, [
                    Element.create('span', {'class': 'bar', 'style':
'width: ' + <same expression> + '%'}),
                    Element.create('span', {'class': 'value-container'},
[values[i]])])
                ])
        );
    }
    element.appendChild(table);

My only complain will be that I had to serialize style attribute. I want to
be able to do:
Element.create('span', {'class': 'bar', 'style': {'width': <same
expression> + '%'}})
instead.

- Ryosuke

Received on Monday, 14 November 2011 03:42:47 UTC