innerHTML and textContent in Go


This post shows how to change the content of a DOM element, i.e., set and get the property innerHTML/textContent of a DOM element. The full code example of this post is on my GitHub.

innerHTML Property of DOM Element

Assume we have the following div element in our HTML

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

We will show how to set/get the innerHTML property of the div element.

JavaScript

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

// set innerHTML
f.innerHTML = "<strong>Hello World</strong>";

// get innerHTML
console.log(f.innerHTML);

GopherJS

The above code in Go/GopherJS is as follows:

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

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

// set innerHTML
f.Set("innerHTML", "<strong>Hello World</strong>")

// get innerHTML
println(f.Get("innerHTML").String())

GopherJS + godom

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

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

f := Document.QuerySelector("#foo")

// set innerHTML
f.SetInnerHTML("<strong>Hello World</strong>")

// get innerHTML
println(f.InnerHTML())

textContent Property of DOM Element

Assume we have the following div element in our HTML

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

We will show how to set/get the textContent property of the div element.

JavaScript

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

// set textContent
f.textContent = "Hello World2";

// get textContent
console.log(f.textContent);

GopherJS

The above code in Go/GopherJS is as follows:

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

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

// set textContent
f.Set("textContent", "Hello World2")

// get textContent
println(f.Get("textContent").String())

GopherJS + godom

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

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

f := Document.QuerySelector("#foo")

// set textContent
f.SetTextContent("Hello World2")

// get textContent
println(f.TextContent())

References:

[1][Golang] GopherJS Synonyms with JavaScript
[2][Golang] GopherJS DOM Example - getElementById and Set innerHTML
[3][Golang] querySelectorAll and querySelector Example by GopherJS