W3C home > Mailing lists > Public > www-dom@w3.org > October to December 2011

Re: Simplifying element creation

From: Bjoern Hoehrmann <derhoermi@gmx.net>
Date: Tue, 15 Nov 2011 00:41:19 +0100
To: Ryosuke Niwa <rniwa@webkit.org>
Cc: Anne van Kesteren <annevk@opera.com>, "www-dom@w3.org" <www-dom@w3.org>
Message-ID: <bg73c712t98mfptug31i9qpgbf2aaim0j8@hive.bjoern.hoehrmann.de>
* Ryosuke Niwa wrote:
>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);

Maybe you are looking for templates, say something like

  <template name='example' white-space='tidy'>
  <tr>
    <td>{0}</td>
    <td>
      <span class='bar' style='width: {1}%'>
        <span class='value-container'>{2}</span>
      </span>
    </td>
  </tr>
  </template>
  ...
  var node = fill("example", labels[i], <some expression>, values[i]);

or with named parameters (make some names up), say,

  var node = fill("example", {
    '0': labels[i],
    '1': <some expression>,
    '2': values[i]
  });

That would seem to suit your use case better.
-- 
Björn Höhrmann · mailto:bjoern@hoehrmann.de · http://bjoern.hoehrmann.de
Am Badedeich 7 · Telefon: +49(0)160/4415681 · http://www.bjoernsworld.de
25899 Dagebüll · PGP Pub. KeyID: 0xA4357E78 · http://www.websitedev.de/ 
Received on Monday, 14 November 2011 23:41:47 GMT

This archive was generated by hypermail 2.2.0+W3C-0.50 : Friday, 22 June 2012 06:14:08 GMT