Dart: Adding child elements to DivElement programmatically

dart, dart-html

Solution

I prefer working with DOM elements using general Dart methods and operations. So, to add a button to a div that is then attached to the body, I would do the following:

import 'dart:html';

void main() {
  var div = new DivElement();
  var button = new ButtonElement()
    ..id = 'foo'
    ..text = 'Foo';
  div.children.add(button);
  document.body.children.add(div);
}

This creates a `ButtonElement` with an `id` and a `text`, appends it to a `DivElement`'s `children`, and appends the `DivElement` to the document body.

Problem

Say I want to add a `ButtonElement` to a `DivElement` programmatically, such that the resultant HTML is: ``` <div class="blah"> <input type="button" name="whatever" value="Push Me!" /> </div> ``` In Dart, I see several methods on the `DivElement` class, and I'm not sure which one is appropriate for which context: ``` ButtonElement button = constructButtonElement(); DivElement div = constructDiv(); div.add(button); div.nodes.add(button); div.children.add(button); // ??? ``` Same goes for any other kind of container: `BodyElement`, `SpanElement`, etc. What's the correct way to dynamically add DOM elements to parent containers?

Original source