[Go WebAssembly] querySelectorAll Example
source link: http://siongui.github.io/2018/10/05/golang-wasm-querySelectorAll/
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.
[Go WebAssembly] querySelectorAll Example
October 05, 2018
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:
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:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK