Ignore non-element nodes when inserting html in a selection

This commit is contained in:
Martin Angers
2021-01-11 18:43:18 -05:00
parent 70a02e53e3
commit 8a11cc402f
2 changed files with 51 additions and 0 deletions

View File

@@ -661,6 +661,9 @@ func (s *Selection) eachNodeHtml(htmlStr string, isParent bool, mergeFn func(n *
if isParent { if isParent {
context = n.Parent context = n.Parent
} else { } else {
if n.Type != html.ElementNode {
continue
}
context = n context = n
} }
if context != nil { if context != nil {

View File

@@ -1,6 +1,7 @@
package goquery package goquery
import ( import (
"log"
"testing" "testing"
) )
@@ -689,3 +690,50 @@ func TestParsingRespectsVaryingContext(t *testing.T) {
oBothA) oBothA)
} }
} }
func TestHtmlWithNonElementNode(t *testing.T) {
const data = `
<html>
<head>
</head>
<body>
<p>
This is <span>some</span><b>text</b>.
</p>
</body>
</html>
`
cases := map[string]func(*Selection, string) *Selection{
"AfterHtml": (*Selection).AfterHtml,
"AppendHtml": (*Selection).AppendHtml,
"BeforeHtml": (*Selection).BeforeHtml,
"PrependHtml": (*Selection).PrependHtml,
"ReplaceWithHtml": (*Selection).ReplaceWithHtml,
"SetHtml": (*Selection).SetHtml,
}
for nm, fn := range cases {
// this test is only to make sure that the HTML parsing/manipulation
// methods do not raise panics when executed over Selections that contain
// non-Element nodes.
t.Run(nm, func(t *testing.T) {
doc := loadString(t, data)
sel := doc.Find("p").Contents()
func() {
defer func() {
if err := recover(); err != nil {
t.Fatal(err)
}
}()
fn(sel, "<div></div>")
}()
// print the resulting document in verbose mode
h, err := OuterHtml(doc.Selection)
if err != nil {
log.Fatal(err)
}
t.Log(h)
})
}
}