goquery Get Number of Children Nodes


Get the number of children nodes via goquery in Golang (Go programming language).

  • Get the number of all children nodes - Use Contents() method
  • Get the number of element children nodes - Use Children() method

Install goquery:

$ go get -u github.com/PuerkitoBio/goquery

Source code:

node.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
33
34
35
36
37
38
39
package main

import (
	"github.com/PuerkitoBio/goquery"
	"strings"
)

const html = `<html>
  <head>
    <title>traverse</title>
  </head>
  <body>
    <div>
      Hello
      <span>World</span>
      <!-- Goquery -->
    </div>
  </body>
</html>`

func NumberOfChild(s *goquery.Selection) int {
	return s.Contents().Length()
	//return s.Contents().Size()
}

func NumberOfElementChild(s *goquery.Selection) int {
	return s.Children().Length()
	//return s.Children().Size()
}

func main() {
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
	if err != nil {
		panic(err)
	}

	println(NumberOfChild(doc.Find("div")))
	println(NumberOfElementChild(doc.Find("div")))
}

Output:

5
1

Tested on: Ubuntu Linux 16.04, Go 1.6.2.


References:

[1]
[2]github.com/PuerkitoBio/goquery - GoDoc