Creating HTML Elements in Dart PRO

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.

Share:

banner for the css playlist in hebrew life michael courses for programmers

The First Steps in CSS

Learn CSS using our our videos (in Hebrew) on the CSS (he) playlist on youtube. Do it now. Do it for free.

Good Trainers Collaborate with Others

It is always essential to keep an open mind and learn from others. This applies to everyone, including teachers and especially software development trainers. Software

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences