css

package
v0.0.0-...-ffbc051 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 27, 2022 License: MIT, MIT Imports: 7 Imported by: 0

README

A CSS selector compiler

GoDoc

This package implements a CSS selector compiler for Go's HTML parsing package golang.org/x/net/html.

package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/ericchiang/css"
	"golang.org/x/net/html"
)

var data = `
<p>
  <h2 id="foo">a header</h2>
  <h2 id="bar">another header</h2>
</p>`

func main() {
	sel, err := css.Compile("h2#foo")
	if err != nil {
		panic(err)
	}
	node, err := html.Parse(strings.NewReader(data))
	if err != nil {
		panic(err)
	}
	for _, ele := range sel.Select(node) {
		html.Render(os.Stdout, ele)
	}
	fmt.Println()
}
$ go run example/css.go
<h2 id="foo">a header</h2>

Details

This package implements the W3 Selectors Level 3 specification. The exact grammar can be found in the grammar.txt file.

Documentation

Overview

Package css implements CSS selector HTML search.

The syntax is that select accepted is the CSS Selector Level 3 spec which is described at https://www.w3.org/TR/css3-selectors/. The parsing grammar is defined the grammar.txt file found within the package.

Selectors compiled by this package search through golang.org/x/net/html nodes and should be used in conjunction with that package.

data := `<p>
  <h2 id="foo">a header</h2>
  <h2 id="bar">another header</h2>
</p>`

sel, err := css.Compile("h2#foo")
if err != nil {
	// handle error
}
node, err := html.Parse(strings.NewReader(data))
if err != nil {
	// handle error
}
elements := sel.Select(node)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Selector

type Selector struct {
	// contains filtered or unexported fields
}

func Compile

func Compile(expr string) (*Selector, error)

func MustCompile

func MustCompile(expr string) *Selector

func (*Selector) Select

func (s *Selector) Select(n *html.Node) []*html.Node

type SyntaxError

type SyntaxError struct {
	Offset int
	// contains filtered or unexported fields
}

func (*SyntaxError) Error

func (s *SyntaxError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL