Dart allows you to create new HTML elements and add them to the web page. There are two ways for doing it. The following code sample shows how to do it.

The code sample includes two files. The first is the HTML file. The second is the Dart file. Once the web browser loads the HTML file it will execute the code we wrote in Dart.

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <title>Creating HTML Element</title>
    <link rel="stylesheet" href="samplenewelements.css">
  </head>
  <body>
    <script type="application/dart" src="samplenewelements.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

The Dart code includes the definition for the main() entry point function. This is the first function that will be executed when the web browser is ready to execute our code in Dart.

import 'dart:html';

void main() {
  var title = new Element.html("<h2>Creating HTML Elements Sample</h2>");
  document.body.children.add(title);
  InputElement input = new Element.tag("input");
  input.id = "username";
  input.placeholder = "enter your username";
  document.body.children.add(input);
  ButtonElement clickHereButton = new Element.tag("button");
  clickHereButton.id = "btn-click-here";
  clickHereButton.text = "Click Here";
  document.body.children.add(clickHereButton);
  Element image = new Element.html("<p><img src='mypix.png'/></p>");
  document.body.children.add(image);
}

The following video clip overviews this code sample, shows its execution and explains it.

You can find more video clips and more resources for learning Dart in my free courses web site at http://abelski.lifemichael.com.

Leave a Reply

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