-
Notifications
You must be signed in to change notification settings - Fork 0
/
attr.go
68 lines (59 loc) · 1.22 KB
/
attr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package dom
import (
"bytes"
"strings"
"golang.org/x/net/html"
)
func GetAttribute(node *html.Node, key string) (string, bool) {
for _, attr := range node.Attr {
if attr.Key == key {
return attr.Val, true
}
}
return "", false
}
func GetAttributeOr(node *html.Node, key string, fallback string) string {
for _, attr := range node.Attr {
if attr.Key == key {
return attr.Val
}
}
return fallback
}
func GetClasses(node *html.Node) []string {
val, found := GetAttribute(node, "class")
if !found {
return nil
}
return strings.Fields(val)
}
func HasID(node *html.Node, expectedID string) bool {
val, found := GetAttribute(node, "id")
if !found {
return false
}
return strings.TrimSpace(val) == expectedID
}
func HasClass(node *html.Node, expectedClass string) bool {
classes := GetClasses(node)
for _, class := range classes {
if class == expectedClass {
return true
}
}
return false
}
// - - - - //
func collectText(n *html.Node, buf *bytes.Buffer) {
if n.Type == html.TextNode {
buf.WriteString(n.Data)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
collectText(c, buf)
}
}
func CollectText(node *html.Node) string {
var buf bytes.Buffer
collectText(node, &buf)
return buf.String()
}