-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdomAPiUtils.go
83 lines (64 loc) · 1.58 KB
/
domAPiUtils.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package goDom
import "slices"
type domAPIUtils struct{}
// check if element matches one level query.
func (u domAPIUtils) elementMatchesQuery(q query, el *Element) bool {
if o := q.operator; o != "" {
switch o {
case query_operator_all:
return true
}
} else {
if q.tagName != "" && el.TagName != q.tagName {
return false
}
if q.id != "" && el.Id != q.id {
return false
}
// check if each class from query contains element
for _, class := range q.classList {
if !slices.Contains(el.ClassList, class) {
return false
}
}
// check if each attribute from query contains element
for k, v := range q.attributes {
attr, ok := el.Attributes[k]
if !ok || (v != "" && v == attr) {
return false
}
}
}
return true
}
// find first element by conditions.
func (u domAPIUtils) findOneByCondition(conditionFn func(*Element) bool, el *Element) (*Element, error) {
for _, child := range el.Children {
if conditionFn(child) {
return child, nil
}
res, err := u.findOneByCondition(conditionFn, child)
if err != nil {
continue
}
return res, nil
}
return nil, notFoundErr{}
}
// find all elements by conditions.
func (u domAPIUtils) findAllByCondition(conditionFn func(*Element) bool, el *Element) ([]*Element, error) {
var matches []*Element
for _, child := range el.Children {
if conditionFn(child) {
matches = append(matches, child)
}
res, err := u.findAllByCondition(conditionFn, child)
if err == nil {
matches = append(matches, res...)
}
}
if len(matches) == 0 {
return nil, notFoundErr{}
}
return matches, nil
}