[Golang] GopherJS DOM Example - Create and Append Element


Introduction

It is really cool to run Go code in the browser. GopherJS is a compiler from Go to JavaScript, which makes this possible. In this post, we will give a simple example of DOM manipulation in Go program. This example shows how to create a new HTML element by createElement method and append it to the DOM tree by appendChild method. If you are not familiar with basic DOM manipulation in Go, read the posts in GopherJS DOM Example series first.

Install GopherJS and DOM bindings

Run the following command to install GopherJS and GopherJS bindings for the JavaScript DOM APIs:

$ go get -u github.com/gopherjs/gopherjs
$ go get -u honnef.co/go/js/dom

Source Code

First we write a simple HTML for our demo:

index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!doctype html>
<html>
<head>
  <title>GopherJS DOM example - Create and Append Element</title>
</head>
<body>

<div id="foo">Click me to create and add new element</div>

<script src="demo.js"></script>
</body>
</html>

We will bind a onclick event handler to the div element whose id is foo. When users click the div element, A new div element will be created and appended to the foo div element.

append.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import "honnef.co/go/js/dom"

func main() {
	d := dom.GetWindow().Document()

	foo := d.GetElementByID("foo").(*dom.HTMLDivElement)
	foo.AddEventListener("click", false, func(event dom.Event) {
		div := d.CreateElement("div").(*dom.HTMLDivElement)
		div.Style().SetProperty("color", "red", "")
		div.SetTextContent("I am new div")
		foo.AppendChild(div)
	})
}

Compile the Go code to JavaScript by:

$ gopherjs build append.go -o demo.js

Put demo.js together with the index.html in the same directory and open the index.html with your browser. Click the text and a new red text will show up!


Tested on: Ubuntu Linux 15.10, Go 1.5.3.