Skip to content

Parse the WrapAllHtml wrapper in the parent's context - #620

Open
abo3losh1 wants to merge 2 commits into
PuerkitoBio:masterfrom
abo3losh1:fix/wrapallhtml-parent-context
Open

abo3losh1 wants to merge 2 commits into
PuerkitoBio:masterfrom
abo3losh1:fix/wrapallhtml-parent-context

Conversation

@abo3losh1

Copy link
Copy Markdown

WrapAllHtml parses the wrapper HTML with the first selected node itself as the context, while the wrapper actually takes that node's place in its parent. WrapHtml already uses the parent.

For most elements that difference is invisible, but not for elements whose content the parser reads as raw text:

doc, _ := goquery.NewDocumentFromReader(strings.NewReader(`<body><textarea>hi</textarea></body>`))
doc.Find("textarea").WrapAllHtml(`<div class="wrap"></div>`)
// body: &lt;div class=&#34;wrap&#34;&gt;&lt;/div&gt;

The wrapper is parsed as text inside a <textarea> context, so it becomes a text node, WrapAllNode moves the textarea into that text node, and the textarea is gone from the document. The same happens with iframe, script, style, title and xmp. WrapHtml on the same input gives <div class="wrap"><textarea>hi</textarea></div>.

If the first node is a text or comment node it panics instead:

doc.Find("p").Contents().WrapAllHtml(`<span></span>`)
// panic: goquery: failed to parse HTML: html: ParseFragment of non-element Node

The fix parses in the parent's context, like WrapHtml. When there is no parent, or the parent is not an element (the document node above <html>), it falls back to parseHtml as before.

Added TestWrapAllHtmlRawTextElement and TestWrapAllHtmlTextNode. The first finds 0 nodes and the second panics before the fix. go test ./... and go vet ./... pass.

WrapAllHtml parsed the wrapper with the first selected node itself as the
context, not its parent. With a textarea, iframe, script, style, title or
xmp the wrapper became a text node and the selection was moved into it,
so the element disappeared from the document. With a text or comment node
it panicked. Use the parent, as WrapHtml does.
Copilot AI balanced review requested due to automatic review settings October 14, 2026 22:14

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants