HTML data-* Attribute in Go


Access HTML data-* attributes of elements in Go/GopherJS. Data attribute of a element allows you to store and retrieve data from the specific element. For example, you may store the information, such as geolocation or time, of an image just in the img element. Data attributes can help you achieve this goal. The full code example of this post is on my GitHub.

Using data-* Attribute

Assume we have the following div element in our HTML:

<div id="foo"></div>

We want to store custom data in the element. We can do the following:

<div id="foo" data-demo-value="hello world"></div>

We add an attribute starting with data- to the element. We can access the data- attribute as follows:

JavaScript

var f = document.querySelector("#foo");

// get value
console.log(f.dataset.demoValue);

// set value
f.dataset.demoValue = "world hello";

The name demo-value in HTML will become demoValue in JavaScript.

GopherJS

The above code in Go/GopherJS is as follows:

import (
      "github.com/gopherjs/gopherjs/js"
)

func main() {
      f := js.Global.Get("document").Call("querySelector", "#foo")

      // get value
      println(f.Get("dataset").Get("demoValue").String())

      // set value
      f.Get("dataset").Set("demoValue", "world hello")
}

GopherJS + godom

To make your code more readable, we can prettify the above code with godom:

import (
      . "github.com/siongui/godom"
)

func main() {
      f := Document.QuerySelector("#foo")

      // get value
      println(f.Dataset().Get("demoValue").String())

      // set value
      f.Dataset().Set("demoValue", "world hello")
}

You can read more detailed tutorial on MDN.


References:

[1][Golang] GopherJS DOM Example - Access HTML Data Attribute