2018-10-24 15:15
浏览 211

如何从Go WebAssembly访问DOM元素属性?

I'm trying to extend the "Hello WebAssembly" example from As given, the example simply prints a message to the console. I wanted to add some code using syscall/js to replace the body element content.

The attempt below fails to build:

package main

import (


func main() {
    fmt.Println("Hello, WebAssembly!") // original example
    // I added
    doc := js.Global().Get("document")
    body := doc.Call("getElementById", "thebody")
    body.innerHTML = "Dynamic Content"

When I try to build with $ env GOOS=js GOARCH=wasm go build -o main.wasm I get : ./wasm.go:14:6: body.innerHTML undefined (type js.Value has no field or method innerHTML)

Not surprising when you think about it, but I don't see an example in the doc at that explains how to get and set element properties.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyannuo7733
    douyannuo7733 2018-10-24 15:32

    To get the value of any property of some JavaScript object, use the Value.Get() method (you actually already used it when you accessed the document object by calling js.Global().Get("document")). Similarly, to set a value of a property, use Value.Set().

    The name of the property whose value to get / set is simply a Go string value, "innerHTML" in your case. The value to be set may be many of Go values (e.g. string, integer numbers, floating point numbers, bool, slices, maps etc.), the js.ValueOf() function is used to obtain a js.Value() that will be set ultimately. In your case, you may simply use the Go string value "Dynamic Content".

    doc := js.Global().Get("document")
    body := doc.Call("getElementById", "thebody")
    body.Set("innerHTML", "Dynamic Content")
    点赞 评论