onehtml for Go
Parse HTML exactly as a browser does, query it with CSS selectors, compute styles, edit it without disturbing a byte the edit didn’t touch, and check it for accessibility, in pure Go.
A quick look
Select elements, read their computed styles, and write an edit back into the original bytes. The result is parsed again to check it.
Getting starteddoc, err := onehtml.Parse(r) links, err := doc.Select("nav a[href^='https://']") styles := doc.Style() for _, a := range links { fmt.Println(a.TextContent(), styles.ComputedStyle(a).Get("color")) } res := onehtml.Rewrite(doc, []onehtml.Edit{ onehtml.SetAttribute(links[0], "rel", "noopener")}) os.Stdout.Write(res.Document)
New in 1.1.1
The declared display before blockification, and fixes that make steps(), object-position and the background-* lists read back as browsers report them. From the changelog:
ComputedStyle.SpecifiedDisplay: the element’sdisplayas declared, in the short formGetuses, before blockification. A float, an absolutely positioned element, the root element and a flex or grid item compute to a block-leveldisplay(CSS Display 3 section 2.7), soGet("display")on a float declaredinline-flexreadsflex;SpecifiedDisplaystill readsinline-flex, which tells a caller the inner display type.steps()keepsjump-start,jump-noneandjump-bothas written when serialized (steps(2, jump-start), no longersteps(2, start));jump-endandendstill read assteps(2).object-positiontakes a unitless0as the offset in its three- and four-value forms (top 0 right 1pxiscalc(100% - 1px) 0px, no longer refused and reset to50% 50%).background-sizecomputes as browsers report it: a single value is the value andauto(10pxis10px auto), twoautos areauto, and lengths are in px (1emis16px auto). A negative or malformed size is invalid.- The
background-*longhand lists (background-position-xand-y,-size,-repeat,-clip,-origin,-attachment,-blend-mode) read back as long as thebackground-imagelist: a longer list is cut, and a shorter one repeats from its start (background-position: left, rightwith one image reads0%forbackground-position-x).
New in 1.1
Registered custom properties, real font metrics for ex, ch, cap and ic, and a report of declarations that are invalid at computed-value time. From the changelog:
Styles.RegistrationsandPropertyRegistration: the document’s@propertyrules (CSS Properties and Values API 1). A registered custom property now takes its initial value when nothing sets it, does not inherit wheninheritsis false, and has a value that does not match its syntax treated as unset; a matching value is computed to its canonical form (calc(1px + 2px)is3px).ResolveAnimationsreports a registered custom property that a keyframe sets, so a caller can interpolate it by its syntax.fonttakes the system font keywords (caption,icon,menu,message-box,small-caption,status-bar), as Chrome reports them on Linux: a 16px Arial in the normal style and weight.- The
tableelement’sborderattribute sets the four border widths (1px when the value does not parse).WithFontMetrics,FontQuery,FontMetricsandFontMetricsFunc: the caller measures the primary font, and theex,ch,capandicunits (and the root-relativerex,rch,rcapandric) take its x-height, zero advance, cap height and ideograph advance. Without it, or for a measurement the function leaves at zero, the estimates stay (half an em, 0.7 em, one em).font-sizeinexis relative to the parent’s font.ComputedStyle.InvalidDeclarationsandStyles.InvalidDeclarations, withInvalidDeclaration: the declarations that won the cascade but are invalid at computed-value time (avar()that does not fit the property, a shorthand that does not expand after substitution, a custom property that refers to nothing or does not fit its registered syntax), with their source.
Upgrading from 1.0
Nothing is removed or deprecated. Some computed values now read back as browsers report them, so code that compares serialized values sees new strings.
The full list under FixedSeveral computed values now read back in the forms browsers report, so code that compared serialized values from 1.0.0 sees new strings: multi-word
font-familynames are quoted,font-stretchis a percentage, a numericline-heightreads as px throughGet(descendants still inherit the number), animation times are in seconds,object-positionandbackground-position-x/-ykeywords become percentages, and px lengths are written with six significant digits. Details under Fixed.
This rule, read back with ComputedStyle(p).Get on each version:
p { font: condensed 16px/1.5 "Open Sans", sans-serif; animation: fade 100ms 200ms; object-position: right bottom; width: calc(40px / 3); }
| Property | v1.0.0 | v1.1.0 |
|---|---|---|
font-family | Open Sans, sans-serif | "Open Sans", sans-serif |
font-stretch | condensed | 75% |
line-height | 1.5 | 24px |
animation-delay | empty | 0.2s |
object-position | right bottom | 100% 100% |
width | 13.333333px | 13.3333px |
The package
- Version
v1.1.1. Go 1.24 or newer.
- Parsing
The WHATWG tokenizer and tree builder in full, fragments and parse errors included, with the Encoding Standard’s detection and decoders. Every node and attribute knows its byte range in the original input.
- CSS
Selectors Level 4; the cascade with origins, layers,
@scope, nesting,@media,@property,var()andcalc(), with computed values asgetComputedStylegives them. No layout, no painting. - Accessibility
The accessibility tree, a reading view and navigation lists, and a checker for WCAG 2.0, 2.1 and 2.2 with JSON, axe-compatible JSON, SARIF and EARL exports.
- Safety
No panic and no hang on any bytes; limits are checked before the work they guard. Opens no files, makes no network requests, never runs script. No cgo, no
unsafe, no dependencies outside the standard library. - License
MIT or Apache-2.0.