...

Source file src/golang.org/x/net/html/iter.go

Documentation: golang.org/x/net/html

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build go1.23
     6  
     7  package html
     8  
     9  import "iter"
    10  
    11  // Ancestors returns an iterator over the ancestors of n, starting with n.Parent.
    12  //
    13  // Mutating a Node or its parents while iterating may have unexpected results.
    14  func (n *Node) Ancestors() iter.Seq[*Node] {
    15  	_ = n.Parent // eager nil check
    16  
    17  	return func(yield func(*Node) bool) {
    18  		for p := n.Parent; p != nil && yield(p); p = p.Parent {
    19  		}
    20  	}
    21  }
    22  
    23  // ChildNodes returns an iterator over the immediate children of n,
    24  // starting with n.FirstChild.
    25  //
    26  // Mutating a Node or its children while iterating may have unexpected results.
    27  func (n *Node) ChildNodes() iter.Seq[*Node] {
    28  	_ = n.FirstChild // eager nil check
    29  
    30  	return func(yield func(*Node) bool) {
    31  		for c := n.FirstChild; c != nil && yield(c); c = c.NextSibling {
    32  		}
    33  	}
    34  
    35  }
    36  
    37  // Descendants returns an iterator over all nodes recursively beneath
    38  // n, excluding n itself. Nodes are visited in depth-first preorder.
    39  //
    40  // Mutating a Node or its descendants while iterating may have unexpected results.
    41  func (n *Node) Descendants() iter.Seq[*Node] {
    42  	_ = n.FirstChild // eager nil check
    43  
    44  	return func(yield func(*Node) bool) {
    45  		n.descendants(yield)
    46  	}
    47  }
    48  
    49  func (n *Node) descendants(yield func(*Node) bool) bool {
    50  	for c := range n.ChildNodes() {
    51  		if !yield(c) || !c.descendants(yield) {
    52  			return false
    53  		}
    54  	}
    55  	return true
    56  }
    57  

View as plain text