8

[Golang] GopherJS DOM Example - Create and Append Element

 2 years ago
source link: https://siongui.github.io/2016/01/14/gopherjs-dom-example-create-and-append-element/
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 - 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
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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK