---
title: "Getting started with onehtml for Go"
url: https://recursiveai.org/onehtml/go/docs/getting-started/
description: "Install the Go module, parse HTML and query it with CSS selectors, read computed styles, edit a page losslessly, build the accessibility tree, check a page against WCAG 2.2 AA, and use @property and font metrics."
version: "1.1.1"
---

# Getting started with onehtml for Go

Install onehtml for Go, parse HTML and query it with CSS selectors, read computed styles, edit a page losslessly, build the accessibility tree and check a page against WCAG.

onehtml for Go parses HTML into the tree a browser builds, matches CSS selectors against it, computes the cascade, and builds the accessibility tree a browser gives screen readers. It does no layout and no painting, opens no files, makes no network requests and never runs script. Every sample on this page was compiled and run with Go 1.26.8 against `recursiveai.org/go/onehtml` v1.1.1 from the Go module proxy; the output under each one is what it printed.

## Install

onehtml needs Go 1.24 or newer.

```sh
mkdir html-start && cd html-start
go mod init example.com/html-start
go get recursiveai.org/go/onehtml@v1.1.1
```

The import path is `recursiveai.org/go/onehtml` and the package name is `onehtml`. The accessibility tree is in `recursiveai.org/go/onehtml/accessibility` and the checker in `recursiveai.org/go/onehtml/accessibility/validation`. The module has no dependencies outside the standard library, no cgo and no `unsafe`. The license is MIT or Apache-2.0, at your choice.

Each sample is a complete `main.go`.

## Parse and select

`Parse` reads from an `io.Reader` and `ParseBytes` from a byte slice. `Select` and `SelectFirst` take Selectors Level 4.

```go
package main

import (
	"fmt"
	"log"
	"strings"

	"recursiveai.org/go/onehtml"
)

const page = `<!doctype html>
<title>Shop</title>
<nav><a href="/">Home</a> <a href="https://example.com/help">Help</a></nav>
<ul class=items>
  <li data-price=4.50>Tea
  <li data-price=12>Coffee &amp; beans
</ul>`

func main() {
	doc, err := onehtml.Parse(strings.NewReader(page))
	if err != nil {
		log.Fatal(err)
	}
	links, err := doc.Select("nav a[href]")
	if err != nil {
		log.Fatal(err)
	}
	for _, a := range links {
		href, _ := a.Get("href")
		fmt.Printf("%-5s %s\n", a.TextContent(), href)
	}

	items, err := doc.Select("ul.items > li")
	if err != nil {
		log.Fatal(err)
	}
	for _, li := range items {
		price, _ := li.Get("data-price")
		fmt.Printf("%q costs %s\n", strings.TrimSpace(li.TextContent()), price)
	}

	// The parser closes the <li> elements and adds <html>, <head> and <body>, as a browser does.
	fmt.Println(items[0].OuterHTML())
	fmt.Println(len(doc.Errors()), "parse errors")
}
```

```text
Home  /
Help  https://example.com/help
"Tea" costs 4.50
"Coffee & beans" costs 12
<li data-price="4.50">Tea
  </li>
0 parse errors
```

- Malformed markup is not an error: whatever the bytes, the result is the tree a browser builds. The parse errors the HTML standard lists are in `doc.Errors()`, with their positions.
- `TextContent` decodes entities, so `&amp;` reads as `&`. `OuterHTML` and `InnerHTML` serialize as the standard says.
- A `Node` is a small value you can copy freely. `Children`, `Descendants` and `Ancestors` are iterators and never recurse, so deep documents can’t exhaust the stack. `CompileSelector` compiles a selector once for reuse.

## Computed styles

`doc.Style()` runs the cascade: the HTML standard’s default style sheet, `<style>` elements, style attributes and presentational hints. `ComputedStyle(n).Get` gives the value `getComputedStyle` would.

```go
package main

import (
	"fmt"
	"log"
	"strings"

	"recursiveai.org/go/onehtml"
)

const page = `<style>
  body { font: 16px/1.5 "Open Sans", sans-serif; color: #333 }
  .note { color: rebeccapurple; padding: 0 1em }
  @media (max-width: 600px) { .note { display: none } }
</style>
<p class=note style="font-weight: bold">Read me</p>`

func main() {
	doc, err := onehtml.Parse(strings.NewReader(page))
	if err != nil {
		log.Fatal(err)
	}
	p, err := doc.SelectFirst("p.note")
	if err != nil {
		log.Fatal(err)
	}

	cs := doc.Style().ComputedStyle(p) // a 1280 x 720 screen by default
	for _, prop := range []string{"color", "font-family", "font-weight", "line-height", "padding-left", "display"} {
		src, _ := cs.Source(prop)
		from := src.Selector
		switch {
		case src.Inherited:
			from = "inherited"
		case src.Initial:
			from = "initial value"
		case src.Origin == onehtml.OriginUserAgent:
			from = "default style sheet"
		case from == "":
			from = "style attribute"
		}
		fmt.Printf("%-13s %-24s %s\n", prop, cs.Get(prop), from)
	}

	// The same page on a phone: the media query now matches.
	phone := doc.Style(onehtml.WithStyleContext(onehtml.StyleContext{ViewportWidth: 390, ViewportHeight: 844}))
	fmt.Println("display at 390px:", phone.ComputedStyle(p).Get("display"))
}
```

```text
color         rgb(102, 51, 153)        .note
font-family   "Open Sans", sans-serif  inherited
font-weight   700                      style attribute
line-height   24px                     inherited
padding-left  16px                     .note
display       block                    default style sheet
display at 390px: none
```

- Values read back in the forms browsers report: colors as `rgb()`, lengths in px, `bold` as `700`. `Source` says which rule, attribute or inherited value won.
- The default context is a 1280 × 720 light-scheme screen. `WithStyleContext` sets the viewport, print, dark scheme, reduced motion and the other media features.
- There is no layout, so values that need it, such as a percentage width, stay as specified. Linked style sheets come from you through `WithStylesheets`; the library never fetches one.

## Edit a page without touching the rest

`Rewrite` turns a list of edits into bytes, splicing each one into the original input. Everything else comes back exactly as it was.

```go
package main

import (
	"fmt"
	"log"
	"strings"

	"recursiveai.org/go/onehtml"
)

// Hand-written markup: unquoted and single-quoted attributes, upper case, a comment, no </p>.
const page = `<P class=intro>Hello, <B>world</B>
<!-- keep me -->
<a href='https://example.com/' target=_blank>Example</a>
<img src=cat.jpg>`

func main() {
	doc, err := onehtml.Parse(strings.NewReader(page))
	if err != nil {
		log.Fatal(err)
	}
	var edits []onehtml.Edit
	links, _ := doc.Select("a[target=_blank]")
	for _, a := range links {
		edits = append(edits, onehtml.SetAttribute(a, "rel", "noopener"))
	}
	imgs, _ := doc.Select("img:not([alt])")
	for _, img := range imgs {
		edits = append(edits, onehtml.SetAttribute(img, "alt", "A cat"))
	}
	b, _ := doc.SelectFirst("b")
	edits = append(edits, onehtml.ReplaceText(b.FirstChild(), "Go"))

	res := onehtml.Rewrite(doc, edits)
	if !res.Applied() {
		log.Fatal(res.Reasons)
	}
	fmt.Println(string(res.Document))
	fmt.Println(len(res.Ranges), "ranges rewritten, checked by", res.Verifications, "reparse")

	// No edits: the output is the input, byte for byte.
	same := onehtml.Rewrite(doc, nil)
	fmt.Println("unchanged:", string(same.Document) == page)
}
```

```text
<P class=intro>Hello, <B>Go</B>
<!-- keep me -->
<a href='https://example.com/' target=_blank rel='noopener'>Example</a>
<img src=cat.jpg alt='A cat'>
3 ranges rewritten, checked by 1 reparse
unchanged: true
```

- The upper-case tags, unquoted attributes, the comment and the missing `</p>` are all still there. The output is parsed again to check that it gives the tree the edits should have made.
- All edits apply or none does; `res.Outcomes` and `res.Reasons` say what happened to each one.
- `doc.Apply` and `doc.Edit` make the same edits on a new snapshot of the tree instead of bytes, and report a `ChangeSet` per commit. The old snapshot stays readable.

## The accessibility tree

`accessibility.Tree` builds the tree a browser exposes to assistive technology, with roles, names and states.

```go
package main

import (
	"fmt"
	"log"
	"strings"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility"
)

const page = `<!doctype html><html lang=en><title>Sign in</title>
<header><nav aria-label=Main><a href=/>Home</a></nav></header>
<main>
  <h1>Sign in</h1>
  <form>
    <label>Email <input type=email required></label>
    <button>Continue</button>
  </form>
  <div hidden>Not shown</div>
</main>`

func main() {
	doc, err := onehtml.Parse(strings.NewReader(page))
	if err != nil {
		log.Fatal(err)
	}
	tree, err := accessibility.Tree(doc)
	if err != nil {
		log.Fatal(err)
	}
	walk(tree.Root(), 0)
}

// walk walks the tree as assistive technology sees it: Exposed skips ignored nodes,
// such as the hidden div, and text nodes are left out here.
func walk(n accessibility.Node, depth int) {
	if !n.IsText() {
		fmt.Printf("%s%s %q\n", strings.Repeat("  ", depth), n.ChromeRole(), n.Name())
		depth++
	}
	for c := range n.Exposed() {
		walk(c, depth)
	}
}
```

```text
RootWebArea "Sign in"
  banner ""
    navigation "Main"
      link "Home"
  main ""
    heading "Sign in"
    form ""
      LabelText ""
        textbox "Email"
      button "Continue"
```

- `Role` is the computed ARIA role; `ChromeRole` is the role as Chrome reports it, including its internal roles such as `LabelText`. The text field takes its name, “Email”, from the label around it.
- The `hidden` div isn’t exposed. Ignored nodes, such as the `<html>` and `<body>` elements, stay in the tree with their reasons (`IgnoredReasons`); `Exposed` steps over them.
- `tree.ReadingView()` and `tree.NavigationLists()` give the page as a reading order and as lists of headings, landmarks, links, form fields and tables.

## Check a page against WCAG

`validation.Check` runs the built-in rules. `WithProfile` limits them to one WCAG version and level.

```go
package main

import (
	"fmt"
	"log"
	"os"
	"strings"

	"recursiveai.org/go/onehtml"
	"recursiveai.org/go/onehtml/accessibility/validation"
)

const page = `<!doctype html><html><title>Gallery</title>
<main>
  <h1>Gallery</h1>
  <img src=cat.jpg>
  <p style="color: #aaa; background: #fff">Light grey text</p>
  <a href=/next></a>
</main>`

func main() {
	doc, err := onehtml.Parse(strings.NewReader(page))
	if err != nil {
		log.Fatal(err)
	}
	report, err := validation.Check(doc, validation.WithProfile(validation.ProfileWCAG22AA))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(report.Count(validation.Failed), "failed,", report.Count(validation.Passed), "passed,",
		report.Count(validation.CantTell), "can't tell")
	for res := range report.WithOutcome(validation.Failed) {
		fmt.Printf("%-24s %-11s %-9s <%s>\n", res.RuleID, strings.Join(res.Rule.Criteria, " "), res.Rule.Impact, res.Target.Name())
	}

	// SARIF for code scanning; WriteJSON, WriteAxeJSON and WriteEARL work the same way.
	f, err := os.Create("report.sarif")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	if err := report.WriteSARIF(f); err != nil {
		log.Fatal(err)
	}
}
```

```text
4 failed, 5 passed, 4 can't tell
color-contrast           1.4.3       serious   <p>
html-has-lang            3.1.1       serious   <html>
image-alt                1.1.1       critical  <img>
link-name                2.4.4 4.1.2 serious   <a>
```

- Each result names the rule, the WCAG success criteria it checks and its impact. The contrast of `#aaa` on white is below 4.5:1.
- “Can’t tell” means a person has to judge, as with whether the title describes the page, or the answer depends on layout, as with `target-size`. `accessibility.ParseFacts` and `validation.WithFacts` take rendered facts from a browser to settle the layout ones.
- `WriteJSON`, `WriteAxeJSON`, `WriteSARIF` and `WriteEARL` export the report.

## Registered custom properties and font metrics

New in 1.1: `@property` rules are applied, invalid declarations are reported, and `WithFontMetrics` gives the `ex`, `ch`, `cap` and `ic` units real values.

```go
package main

import (
	"fmt"
	"log"
	"strings"

	"recursiveai.org/go/onehtml"
)

const page = `<style>
  @property --gap { syntax: "<length>"; inherits: false; initial-value: 8px }
  .card { --gap: calc(1px + 2px); padding: var(--gap); width: 20ch }
  .card p { padding: var(--gap); margin: var(--missing) }
  .bad { --gap: red; padding: var(--gap) }
</style>
<div class=card><p>Inside</p></div>
<div class=bad></div>`

func main() {
	doc, err := onehtml.Parse(strings.NewReader(page))
	if err != nil {
		log.Fatal(err)
	}

	// The caller measures fonts; here a zero advance of 0.55 em for every font.
	metrics := func(q onehtml.FontQuery) onehtml.FontMetrics {
		return onehtml.FontMetrics{ZeroAdvance: 0.55}
	}
	styles := doc.Style(onehtml.WithFontMetrics(metrics))

	for _, r := range styles.Registrations() {
		fmt.Printf("@property %s %s inherits=%v initial=%s\n", r.Name, r.Syntax, r.Inherits, r.InitialValue)
	}
	for _, sel := range []string{".card", ".card p", ".bad"} {
		n, _ := doc.SelectFirst(sel)
		cs := styles.ComputedStyle(n)
		fmt.Printf("%-7s --gap %-4s padding-top %-4s width %s\n", sel, cs.Get("--gap"), cs.Get("padding-top"), cs.Get("width"))
	}

	// Declarations that won the cascade but have no value at computed-value time.
	for n, bad := range styles.InvalidDeclarations() {
		fmt.Printf("<%s> %s: %s  (from %s)\n", n.Name(), bad.Property, bad.Value, bad.Source.Selector)
	}
}
```

```text
@property --gap <length> inherits=false initial=8px
.card   --gap 3px  padding-top 3px  width 176px
.card p --gap 8px  padding-top 8px  width auto
.bad    --gap 8px  padding-top 8px  width auto
<p> margin: var(--missing)  (from .card p)
<div> --gap: red  (from .bad)
```

- `--gap` is registered as a `<length>`, so `calc(1px + 2px)` computes to `3px`. It doesn’t inherit, so the `<p>` inside the card gets the initial `8px`, and `red` doesn’t fit the syntax, so `.bad` gets `8px` too.
- With the font metrics, `20ch` at 16px is 20 × 0.55 × 16 = `176px`. Without them, `ch` is estimated at half an em.
- `InvalidDeclarations` lists the declarations that won the cascade but have no value at computed-value time, with their source. `ComputedStyle.InvalidDeclarations` does the same for one element.

## Where next

- [Overview](https://recursiveai.org/onehtml/go/docs/overview/): the README, with the quick start and the packages.
- [Changelog](https://recursiveai.org/onehtml/go/docs/changelog/): what changed in 1.1.0 and 1.1.1.
- [Package documentation](https://pkg.go.dev/recursiveai.org/go/onehtml) on pkg.go.dev, with an example for each feature.
