WASM and DOM
- Go course
- Expert
- Lesson 27/34
- 4 min
Learn to access the DOM with the js package.
WASM and the DOM
The syscall/js package accesses JavaScript objects from Go. js.Global() is the browser's window object:
doc := js.Global().Get("document")
el := doc.Call("getElementById", "sonuc")
el.Set("textContent", "Go'dan merhaba")To make a Go function callable from JS use js.FuncOf; to keep the program alive, main ends with select {}.
Events with js.FuncOf
Running Go code when a button is clicked:
topla := js.FuncOf(func(this js.Value, args []js.Value) any {
return args[0].Int() + args[1].Int()
})
js.Global().Set("goTopla", topla)
// JavaScript: goTopla(2, 3) → 5Call Release() when a js.Func is no longer needed, otherwise it stays in memory. Every call between Go and JS is costly; avoid frequent crossings.
Practice Callback signature
Since syscall/js only compiles for WASM, imitate the signature: write type Deger struct{ n int } and func topla(args []Deger) any that adds the n of the first two arguments. Print topla([]Deger{{2}, {3}}).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Deger struct{ n int }
func topla(args []Deger) any {
return args[0].n + args[1].n
}
func main() {
fmt.Println(topla([]Deger{{2}, {3}}))
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why does a Go WASM program end with <code>select {}</code>?
- To load the DOM
- If main returns the program exits and Go functions given to JS stop working Correct answer
- To improve performance
- To catch errors
Explanation: select {} waits forever, so the runtime stays alive and event callbacks are handled.
2 Call a JS method
el := js.Global().Get("document").____("getElementById", "kutu")
el := js.Global().Get("document").Call("getElementById", "kutu")
Explanation: Call invokes a JS object's method with the given arguments.
3 syscall/js
| Term | Meaning |
|---|---|
js.Global() |
The window object |
Get |
Reads a property |
Set |
Writes a property |
js.FuncOf |
Exposes a Go function to JS |