Yes, you can modify an HTML document with GoQuery, a package in Go (Golang) which is inspired by jQuery. GoQuery provides a set of methods to manipulate the DOM (Document Object Model) similar to how you would with jQuery in JavaScript.
Here's a simple example of how you might use GoQuery to modify an HTML document:
package main
import (
"fmt"
"github.com/PuerkitoBio/goquery"
"strings"
)
func main() {
// Sample HTML
html := `<html>
<head>
<title>Sample Page</title>
</head>
<body>
<p id="paragraph">Hello, World!</p>
</body>
</html>`
// Create a new document from the HTML string
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
fmt.Printf("Error creating document: %v\n", err)
return
}
// Modify the text of the paragraph
doc.Find("#paragraph").SetText("Hello, GoQuery!")
// Add a new class to the paragraph
doc.Find("#paragraph").AddClass("new-class")
// Append a new element
doc.Find("body").AppendHtml("<div>New Div</div>")
// Print the modified HTML
modifiedHtml, err := doc.Html()
if err != nil {
fmt.Printf("Error generating HTML: %v\n", err)
return
}
fmt.Println(modifiedHtml)
}
In this example, we are:
- Creating a new GoQuery document from a string containing HTML.
- Using the
Find
method to locate the paragraph element with the ID ofparagraph
. - Changing the text inside the paragraph to "Hello, GoQuery!" using the
SetText
method. - Adding a new class to the paragraph with
AddClass
. - Appending a new
<div>
element to the<body>
usingAppendHtml
. - Finally, we output the modified HTML.
Make sure you have GoQuery installed in your environment to run the above code. You can install it with the following command:
go get github.com/PuerkitoBio/goquery
Remember that GoQuery is mainly used for parsing and extracting data from HTML, and while it can modify HTML documents, it is not as feature-rich or intended for heavy HTML document manipulation like a browser-based DOM manipulation library. For more complex or dynamic DOM manipulations, using JavaScript with a frontend library like jQuery or a virtual DOM library like React might be more suitable.