goquery BeforeHtml doesn't add element

136 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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)