[Golang] GopherJS DOM Example - getElementById and Set innerHTML


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 very simple example of DOM manipulation in Go program. This example uses getElementById to access DOM element and set innerHTML of the element.

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
<!doctype html>
<html>
<head>
  <title>GopherJS DOM example - getElementById() and innerHTML</title>
</head>
<body>
  <div id="foo"></div>
  <script src="dom.js"></script>
</body>
</html>

We will access the div element whose id is foo. Then add Hello World text to the div. Now write a Go program to manipulate DOM:

dom.go | repository | view raw
1
2
3
4
5
6
7
8
9
package main

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

func main() {
	d := dom.GetWindow().Document()
	h := d.GetElementByID("foo")
	h.SetInnerHTML("Hello World")
}

It is very easy and intuitive. Compile the Go code to JavaScript:

$ gopherjs build dom.go -o dom.js

Put dom.js together with the index.html in the same directory and open the index.html with your browser. You will see Hello World in the browser window.


Tested on: Ubuntu Linux 15.10, Go 1.5.2.