mirror of
https://github.com/PuerkitoBio/goquery
synced 2025-12-24 12:38:00 +08:00
Ignore non-element nodes when inserting html in a selection
This commit is contained in:
@@ -661,6 +661,9 @@ func (s *Selection) eachNodeHtml(htmlStr string, isParent bool, mergeFn func(n *
|
||||
if isParent {
|
||||
context = n.Parent
|
||||
} else {
|
||||
if n.Type != html.ElementNode {
|
||||
continue
|
||||
}
|
||||
context = n
|
||||
}
|
||||
if context != nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package goquery
|
||||
|
||||
import (
|
||||
"log"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -689,3 +690,50 @@ func TestParsingRespectsVaryingContext(t *testing.T) {
|
||||
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)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user