1

Why does the following test fail?

func TestGetFirstElementHtml(t *testing.T) {
    test := `<speak><p>My paragraph</p></speak>`
    doc, _ := goquery.NewDocumentFromReader(strings.NewReader(test))
    var childrenHtml []string
    doc.Find("speak").Children().Each(func(i int, s *goquery.Selection) {
        html, _ := s.Html()
        childrenHtml = append(childrenHtml, html)
    })
    if childrenHtml[0] != "<p>My paragraph</p>" {
        t.Fatalf("First element html is not valid: '%s'", childrenHtml[0])
    }
}

This is the test result:

=== FAIL: . TestGetFirstElementHtml (0.00s)
    main_test.go:45: First element html is not valid: 'My paragraph'

In other words, how can I retrieve the full HTML of the first child of given that I cannot predict what kind html element that child is?

Alexander van Trijffel
  • 2,916
  • 1
  • 29
  • 31

1 Answers1

2

What you want is actually outer HTML, and you can get it by calling goquery.OuterHTML function. As per document:

func OuterHtml(s *Selection) (string, error)

OuterHtml returns the outer HTML rendering of the first item in the selection - that is, the HTML including the first element's tag and attributes.

Unlike InnerHtml, this is a function and not a method on the Selection, because this is not a jQuery method (in javascript-land, this is a property provided by the DOM).

So just change the line to:

html, _ := goquery.OuterHTML(s)
leaf bebop
  • 7,643
  • 2
  • 17
  • 27