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

Xiaoru Li
InstructorXiaoru Li
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 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.

egghead
egghead
~ 17 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today