[GopherJS] Traverse DOM Tree


Traverse DOM tree in place via GopherJS.

traverse.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

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

func traverse(elm *js.Object) {
	nodeType := elm.Get("nodeType").Int()

	if nodeType == 1 || nodeType == 9 {
		// element node or document node
		childNodesList := elm.Get("childNodes")
		length := childNodesList.Get("length").Int()
		for i := 0; i < length; i++ {
			// recursively call to traverse
			traverse(childNodesList.Call("item", i))
		}
		return
	}

	if nodeType == 3 {
		// text node
		s := elm.Get("nodeValue").String()
		println(s)
		return
	}
}

func main() {
	doc := js.Global.Get("document")
	traverse(doc)
}

If you want to access other nodeType, see [2].


References:

[1]GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, godoc)
[2][GopherJS] Check nodeType of DOM Element