[Go WebAssembly] querySelectorAll Example


In this post, we will show you how to use querySelectorAll 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 div elements by querySelectorAll, and set the value of its innerHTML to hi. See demo first:

Go Wasm querySelectorAll Demo

The following is source code of demo:

Go:

package main

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

func main() {
      testdivs := Document.QuerySelectorAll("#testdivs > div")
      for _, testdiv := range testdivs {
              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 - querySelectorAll</title>
</head>
<body>
  <div id="testdivs">
    <div></div>
    <div></div>
    <div></div>
  </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 elements inside the element whose id is testdivs. Most of the HTML code is to load compiled wasm module. If you have no idea what it means, see [1].

For querySelector 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] querySelector Example