querySelector, querySelectorAll, getElementById in Go


This post shows you how to querySelector, querySelectorAll, and getElementById to get the element(s) we need in the DOM tree for further processing via Go/GopherJS. If you need offile HTML processing library, you can take a look at goquery or soup on GitHub.

querySelector

JavaScript

querySelector returns a DOM element. The following JavaScript code returns the element with id foo:

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

GopherJS

The above code in Go/GopherJS is as follows:

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

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

GopherJS + godom

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

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

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

querySelectorAll

JavaScript

querySelectorAll returns a NodeList. The following code selects all div elements in the document.

var nodeList = document.querySelectorAll("div");
for (var i = 0; i < nodeList.length; ++i) {
  var elm = nodeList[i];
  // do something with the element
}

GopherJS

The above code in Go/GopherJS is as follows:

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

d := js.Global.Get("document")
nodeList := d.Call("querySelectorAll", "div")
length := nodeList.Get("length").Int()
for i := 0; i < length; i++ {
      elm := nodeList.Call("item", i)
      // do something with the element
}

GopherJS + godom

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

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

nodeList := Document.QuerySelectorAll("div")
for _, elm := range nodeList {
      // do something with the element
}

getElementById

JavaScript

The following code returns the element with id foo.

var element = document.getElementById("foo");

GopherJS

The above code in Go/GopherJS is as follows:

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

element := js.Global.Get("document").Call("getElementById", "foo")

GopherJS + godom

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

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

element := Document.GetElementById("foo")

References:

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