[Golang] GopherJS DOM Example - Access HTML Data Attribute
source link: http://siongui.github.io/2016/01/12/gopherjs-dom-example-access-html-data-attribute/
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
If you have following element in HTML:
<div id="foo" data-my-demo-value="Hey"></div>
Access the value by Dataset() function, which returns map[string]string:
import "honnef.co/go/js/dom" ... d := dom.GetWindow().Document() div1 := d.GetElementByID("foo").(*dom.HTMLDivElement) v := div1.Dataset()["myDemoValue"]
Note that data-my-demo-value becomes myDemoValue when accessed. Full example is as follows:
HTML:
index.html | repository | view raw
<!doctype html> <html> <head> <title>GopherJS DOM example - Access HTML Data Attribute</title> </head> <body> <div id="foo" data-my-demo-value="Hey"></div> <div id="foo2" data-hello="world"></div> <script src="demo.js"></script> </body> </html>
Go:
data.go | repository | view raw
package main import "honnef.co/go/js/dom" func main() { d := dom.GetWindow().Document() div1 := d.GetElementByID("foo").(*dom.HTMLDivElement) print(div1.Dataset()["myDemoValue"]) div2 := d.GetElementByID("foo2").(*dom.HTMLDivElement) print(div2.Dataset()["hello"]) }
Compile the Go code to JavaScript by:
$ gopherjs build data.go -o demo.js
Put demo.js together with the index.html in the same directory and open the index.html with your browser. Open the browser console and you will see the printed value.
Tested on: Ubuntu Linux 15.10, Go 1.5.2.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK