Interact with the DOM using Go's `syscall/js` module

Xiaoru Li
InstructorXiaoru Li

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 2 years ago

Go ^1.12

The ability to manipulate the DOM is sometimes crucial when it comes to working with apps powered by WebAssembly. In this lesson, we will see how we can utilize Go's syscall/js module to interact with the DOM by porting a sample JS code snippet to Go.

Xiaoru Li: [0:00] The DOM methods can be accessed like normal JavaScript functions in Go with the syscall/js module. Let's get the document object in the browser first by running js.Global().Get("document").

[0:15] Then, we can create a new H1 header element by doing document.Call("createElement"), then pass in the parameter h1. We can then set the innerText property of the header element to This is H1. Finally, we can append the H1 note to the body of the DOM.

[0:40] Let's Compile and test it. Here we go. As you can see, our Go code is exactly equivalent to its JavaScript counterpart here. We can then follow this explicit Get Call Set method call pattern to interact with the DOM, just like we do in normal JavaScript.