github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zhttp/query_render.go (about)

     1  package zhttp
     2  
     3  import (
     4  	"bytes"
     5  	"strings"
     6  
     7  	"golang.org/x/net/html"
     8  )
     9  
    10  func (e Els) ForEach(f func(index int, el QueryHTML) bool) {
    11  	for i, v := range e {
    12  		if !f(i, v) {
    13  			break
    14  		}
    15  	}
    16  }
    17  
    18  func (r QueryHTML) String() string {
    19  	return r.HTML(true)
    20  }
    21  
    22  func (r QueryHTML) Exist() bool {
    23  	return r.node != nil && r.node.Data != ""
    24  }
    25  
    26  func (r QueryHTML) Attr(key string) string {
    27  	return r.Attrs()[key]
    28  }
    29  
    30  func (r QueryHTML) Attrs() map[string]string {
    31  	node := r.getNode()
    32  	if node.Type != html.ElementNode || len(node.Attr) == 0 {
    33  		return make(map[string]string)
    34  	}
    35  	return getAttrValue(node.Attr)
    36  }
    37  
    38  func (r QueryHTML) Name() string {
    39  	return r.getNode().Data
    40  }
    41  
    42  func (r QueryHTML) Text(trimSpace ...bool) string {
    43  	text := getElText(r, false)
    44  	if len(trimSpace) > 0 && trimSpace[0] {
    45  		text = strings.TrimSpace(text)
    46  	}
    47  	return text
    48  }
    49  
    50  func (r QueryHTML) FullText(trimSpace ...bool) string {
    51  	text := getElText(r, true)
    52  	if len(trimSpace) > 0 && trimSpace[0] {
    53  		text = strings.TrimSpace(text)
    54  	}
    55  	return text
    56  }
    57  
    58  func (r QueryHTML) HTML(trimSpace ...bool) string {
    59  	var b bytes.Buffer
    60  	if err := html.Render(&b, r.getNode()); err != nil {
    61  		return ""
    62  	}
    63  	text := b.String()
    64  	if len(trimSpace) > 0 && trimSpace[0] {
    65  		text = strings.TrimSpace(text)
    66  	}
    67  	return text
    68  }