Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: Adding child elements to DivElement programmatically

Tags:

dart

dart-html

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?

like image 650
IAmYourFaja Avatar asked Dec 29 '13 15:12

IAmYourFaja


1 Answers

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.

like image 81
Shailen Tuli Avatar answered Nov 05 '22 08:11

Shailen Tuli