我试图使用"github.com/PuerkitoBio/goquery“在另一个html元素之前插入html元素。不幸的是,没有添加新元素。
package main
import (
"os"
"strings"
"github.com/PuerkitoBio/goquery"
)
var html = `
<section>
<article>
<h2>Article 1</h2>
<p>Text for article #1</p>
</article>
<article>
<h2>Article 2</h2>
<p>Text for article #2</p>
</article>
</section>
`
func main() {
qHtml, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
panic(err)
}
section := qHtml.Find(`section`)
section.BeforeHtml(`<h1>Team Supreme</h1>`)
goquery.Render(os.Stdout, section)
}如果我替换
section.BeforeHtml(`<h1>Team Supreme</h1>`)使用
section = section.BeforeHtml(`<h1>Team Supreme</h1>`)不知道什么是正确的方法。
发布于 2022-05-12 03:54:53
BeforeHtml正在按预期工作,它不可见,因为您只呈现选定的节标记及其内容,但是附加的h1元素在其前面,以使附加的h1标记可见,您必须在下面的行中更新。
goquery.Render(os.Stdout, section)至
goquery.Render(os.Stdout, qHtml.Selection)https://stackoverflow.com/questions/72192658
复制相似问题