goquery replace html element with ReplaceWithSelection has not affect

418 Views Asked by At

✌️

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

There are 1 best solutions below

0
On

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