---
title: "Parse an HTML fragment with element context in Go"
url: https://recursiveai.org/onehtml/go/cookbook/parse-html-fragment-in-context/
description: "Parse HTML as the contents of an element in Go. Use a tbody context to read table rows, or derive context from an existing node."
version: "1.1.1"
---

# Parse an HTML fragment with element context in Go

**onehtml-go** is a free, open-source HTML parser for Go from Recursive AI, with CSS selectors, computed styles, lossless editing and accessibility checks. MIT or Apache-2.0, no dependencies.

[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onehtml) · [GitHub](https://github.com/recursive-ai-oss/onehtml-go) · [Docs](https://recursiveai.org/onehtml/go/docs/) · [Download example (.zip)](https://recursiveai.org/onehtml/go/cookbook/parse-html-fragment-in-context/parse-html-fragment-in-context.zip)

Pass `ParseFragmentBytes` the intended parent as context. For table rows, use `tbody`.

```shell
go get recursiveai.org/go/onehtml
```

Requires Go 1.24 or later.

```go
package main

import (
	"fmt"
	"recursiveai.org/go/onehtml"
)

func main() {
	ctx := onehtml.FragmentContext{
		Name:      "tbody",
		Namespace: onehtml.HTML,
	}
	row := []byte(`<tr><td>Tea</td></tr>`)
	frag, err := onehtml.ParseFragmentBytes(row, ctx)
	if err != nil {
		panic(err)
	}
	node := frag.Root().FirstChild()
	fmt.Println(node.Name(), node.TextContent())
}
```

If you use a `body` context instead of `tbody`, the standalone row markup can be dropped during parsing.

Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onehtml`, then `go run .`; or unzip [the example](https://recursiveai.org/onehtml/go/cookbook/parse-html-fragment-in-context/parse-html-fragment-in-context.zip) and `go run .`.

`go run .` prints:

```text
tr Tea
```

## Variations

If the destination is already in a document, derive its context from that node. Add this after the code above, inside `main`, because it reuses `row`, `ctx`, and `frag`. It prints `tr` again.

```go
page, err := onehtml.ParseBytes([]byte(
    `<table><tbody id="rows"></tbody></table>`,
))
if err != nil { panic(err) }
target := page.ElementByID("rows")
if !target.Valid() { panic("#rows not found") }
ctx = onehtml.FragmentContextOf(target)
frag, err = onehtml.ParseFragmentBytes(row, ctx)
if err != nil { panic(err) }
fmt.Println(frag.Root().FirstChild().Name())
```

## Related recipes

- [Get computed CSS styles without a browser in Go](https://recursiveai.org/onehtml/go/cookbook/compute-css-style-without-browser/)
- [Edit HTML attributes without reformatting in Go](https://recursiveai.org/onehtml/go/cookbook/edit-html-attributes-without-reformatting/)

## The short answer

Call `onehtml.ParseFragmentBytes` with the fragment and the element that would contain it. For rows, use `onehtml.FragmentContext{Name: "tbody", Namespace: onehtml.HTML}`. If you already have the parent as a node, derive its context with `onehtml.FragmentContextOf(parent)` instead. Read the parsed nodes under `frag.Root()`.

## How do I parse an HTML fragment in Go without losing table tags?

Choose the parent that makes sense for the fragment, not the first tag in the fragment itself. A `tbody` contains the sample’s `tr`; a `tr` is the context when the fragment consists of `td` cells. A body is not a generic context that preserves any tags you give it. A bare `<tr>` in a body can lose its row tag under HTML’s error recovery. With the table-body context, the parser starts in the right mode to keep the row and cell. See the [HTML fragment parsing algorithm](https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments) for how context sets the starting mode.

No wrapper is needed in the fragment input. The example supplies `<tr><td>Tea</td></tr>` and reads the row under the returned fragment root. That root isn’t a `<tbody>` or a copy of an existing table. It’s a container for what the parser produced, which is why the first child in the example is already `tr`. The parser can still repair malformed HTML inside the fragment; context is not a switch that turns error recovery off.

## How do I parse HTML as if I were setting innerHTML?

When the parent is an actual element in a parsed page, `FragmentContextOf` captures more than the tag name. It includes the namespace, the document’s quirks mode, and whether the element is inside a form. In a form context, a second `<form>` start tag can be ignored. If you recreated the parent from only its name, that bit of surrounding state could be lost. The helper also captures whether a MathML `annotation-xml` element is an HTML integration point.

The function models how the content is *parsed*; it does not assign anything to the original page. Use the returned tree to inspect or select the new nodes. Both fragment parsing entry points expect UTF-8. If your starting point is an entire document in an unknown legacy encoding, use the whole-document parser to interpret those bytes first rather than giving them to the fragment parser.
