goquery thehhtml dy not not

发布于 2025-01-27 19:19:10 字数 1100 浏览 3 评论 0原文

我正在尝试使用“ github.com/puerkitobio/goquery”之前插入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>`)

正确的方法是什么是正确的方法,

I am trying to insert an html element before another html element using "github.com/PuerkitoBio/goquery". Unfortunately, the new element is not added ????

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)
}

The same is true if I replace

section.BeforeHtml(`<h1>Team Supreme</h1>`)

with

section = section.BeforeHtml(`<h1>Team Supreme</h1>`)

Not sure what is the right way of doing it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空心↖ 2025-02-03 19:19:10

它不可见,因为您仅渲染选定的部分标签及其内容,但是附加的h1元素是在其进行附加h1标签之前可见

goquery.Render(os.Stdout, section)

goquery.Render(os.Stdout, qHtml.Selection)

BeforeHtml is working as expected it is not visible since you are only rendering selected section tag and its content but the appended h1 element is before it to make appended h1 tag visible you have to update below line

goquery.Render(os.Stdout, section)

To

goquery.Render(os.Stdout, qHtml.Selection)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文