goquery替换html元素用replactwithSelection没有影响

发布于 2025-01-28 07:13:38 字数 874 浏览 3 评论 0原文

✌️

我试图使用“ github.com/puerkitobio/goquery”替换HTML父元素的子元素。但是,替换为WithSelection不会替换任何东西,并且选择保持不变。

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`)
    sectionChildren := section.Children().Clone()
    section.ReplaceWithSelection(sectionChildren)

    goquery.Render(os.Stdout, section)
}

✌️

I am trying to replace an html parent element with its child elements using "github.com/PuerkitoBio/goquery". However, ReplaceWithSelection does not replace anything and the selection remains unchanged.

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`)
    sectionChildren := section.Children().Clone()
    section.ReplaceWithSelection(sectionChildren)

    goquery.Render(os.Stdout, section)
}

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

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

发布评论

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

评论(1

≈。彩虹 2025-02-04 07:13:38

由于仅引用实际文档中的一个孩子,我们在其中使用 replacewithSelection 这些更改将反映在实际文档中,而不是可以从实际文档替换的参考文献,但由于您仍然有参考,因此您将使用实际更改查看它。

要查看更改,而不是使用使用文档在其中完成了更改。

更改

goquery.Render(os.Stdout, section)

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

Since section just references one of the children in actual Document on which we are using ReplaceWithSelection the changes will be reflected in actual Document instead of reference which may have be replaced from actual Document but since you have the reference still you are to view it with the actual changes.

To view the changes instead of using section use Document on which the changes are done.

Change

goquery.Render(os.Stdout, section)

To

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