From 8a11cc402f4131d3cd284c1a496cf1d7ccf8da33 Mon Sep 17 00:00:00 2001 From: Martin Angers Date: Mon, 11 Jan 2021 18:43:18 -0500 Subject: [PATCH] Ignore non-element nodes when inserting html in a selection --- manipulation.go | 3 +++ manipulation_test.go | 48 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/manipulation.go b/manipulation.go index 2c31770..35febf1 100644 --- a/manipulation.go +++ b/manipulation.go @@ -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 { diff --git a/manipulation_test.go b/manipulation_test.go index 74dda7c..1119689 100644 --- a/manipulation_test.go +++ b/manipulation_test.go @@ -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 = ` + + + + +

+ This is sometext. +

+ + +` + + 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, "
") + }() + + // print the resulting document in verbose mode + h, err := OuterHtml(doc.Selection) + if err != nil { + log.Fatal(err) + } + t.Log(h) + }) + } +}