Create and Append Element or Text Node in Go


This post shows how to create an DOM element or text node, and then append the element or text node to another element. We will show you how to use createElement, createTextNode, and appendChild methods in Go/GopherJS. The full code example of this post is on my GitHub.

Create/Append Element or Text Node

Assume we have the following div element in our HTML:

<div id="foo"></div>

We will create a span element and append it to the div element. Then we create a text node whose content is Hello World, and append it to the span element.

JavaScript

var f = document.querySelector("#foo");

var s = document.createElement("span");
f.appendChild(s);

var t = document.createTextNode("Hello World");
s.appendChild(t);

GopherJS

The above code in Go/GopherJS is as follows:

import (
      "github.com/gopherjs/gopherjs/js"
)

func main() {
      f := js.Global.Get("document").Call("querySelector", "#foo")

      // create element
      s := js.Global.Get("document").Call("createElement", "span")
      // append element
      f.Call("appendChild", s)

      // create text node
      t := js.Global.Get("document").Call("createTextNode", "Hello World")
      // append text node
      s.Call("appendChild", t)
}

GopherJS + godom

To make your code more readable, we can prettify the above code with godom:

import (
      . "github.com/siongui/godom"
)

func main() {
      f := Document.QuerySelector("#foo")

      // create element
      s := Document.CreateElement("span")
      // append element
      f.AppendChild(s)

      // create text node
      t := Document.CreateTextNode("Hello World")
      // append text node
      s.AppendChild(t)
}

References:

[1][GopherJS] createElement and createTextNode DOM Example
[2][Golang] GopherJS DOM Example - Create and Append Element