[Go WebAssembly] querySelector Example


In this post, we will show you how to use querySelector method in Go wasm. godom package is used for DOM manipulation instead of using syscall/js directly. First install godom:

$ GOARCH=wasm GOOS=js go get -u github.com/siongui/godom/wasm

We will select an element whose id is testdiv, and set the value of its innerHTML to hi. See demo first:

Go Wasm querySelector Demo

The following is source code of demo:

Go:

package main

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

func main() {
      testdiv := Document.QuerySelector("#testdiv")
      testdiv.Set("innerHTML", "hi")
}

If you have experience of JavaScript DOM manipulation, the above code is self-evident. If you do not know how to compile the code, see [1].

HTML:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Go wasm - querySelector</title>
</head>
<body>
  <div id="testdiv"></div>

  <!-- https://github.com/golang/go/blob/master/misc/wasm/wasm_exec.js -->
  <script src="wasm_exec.js"></script>
  <script>
      const go = new Go();
      let mod, inst;
      WebAssembly.instantiateStreaming(
              fetch("query.wasm", {cache: 'no-cache'}), go.importObject).then((result) => {
              mod = result.module;
              inst = result.instance;
              run();
      });
      async function run() {
              await go.run(inst);
      };
  </script>
</body>
</html>

We manipulate the div element whose id is testdiv. Most of the HTML code is to load compiled wasm module. If you have no idea what it means, see [1].

For querySelectorAll example, see [2].

The full source code is also available in my GitHub repo.


Tested on:

  • Ubuntu Linux 18.04
  • Go 1.11.1
  • Chromium Version 69.0.3497.81 on Ubuntu 18.04 (64-bit)

References:

[1](1, 2) [Go WebAssembly] First Wasm Program - Hello World
[2][Go WebAssembly] querySelectorAll Example