Skip to content

x/net/html: add Node methods Ancestors, ChildNodes, Descendants #62113

@earthboundkid

Description

@earthboundkid

This is assuming #61405 is accepted.

Iterating through all the children of an html.Node is tedious. The current code has this example of a recursive function printing out links:

var f func(*html.Node)
f = func(n *html.Node) {
	if n.Type == html.ElementNode && n.Data == "a" {
		for _, a := range n.Attr {
			if a.Key == "href" {
				fmt.Println(a.Val)
				break
			}
		}
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		f(c)
	}
}
f(doc)

It would be much nicer with an iterator:

for n := range doc.All() {
	if n.Type == html.ElementNode && n.Data == "a" {
		for _, a := range n.Attr {
			if a.Key == "href" {
				fmt.Println(a.Val)
				break
			}
		}
	}
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Accepted

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions