Skip to content

Commit

Permalink
Ignore non-element nodes when inserting html in a selection
Browse files Browse the repository at this point in the history
  • Loading branch information
mna committed Jan 11, 2021
1 parent 70a02e5 commit 8a11cc4
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
3 changes: 3 additions & 0 deletions manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
48 changes: 48 additions & 0 deletions manipulation_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package goquery

import (
"log"
"testing"
)

Expand Down Expand Up @@ -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)
})
}
}

0 comments on commit 8a11cc4

Please sign in to comment.