7

[Golang] GopherJS DOM Example - getElementById and Set innerHTML

 2 years ago
source link: http://siongui.github.io/2016/01/10/gopherjs-dom-example-getElementById-innerHTML/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Source Code

First we write a simple HTML for our demo:

index.html | repository | view raw

<!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

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK