-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_and_detach_node.go
56 lines (50 loc) · 1.35 KB
/
find_and_detach_node.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
package main
import (
"strings"
"golang.org/x/net/html"
)
// findAndDetachNode searches and detaches a node by id.
// It returns the detached node and a boolean indicating if the operation was successful.
func findAndDetachNode(n *html.Node, id string, doDetach bool) (*html.Node, bool) {
var parent *html.Node
var nodeToDetach *html.Node
var traverse func(*html.Node) bool
traverse = func(n *html.Node) bool {
if n.Type == html.ElementNode {
for _, a := range n.Attr {
if a.Key == "id" && a.Val == id {
nodeToDetach = n
return true
} else if a.Key == "class" && strings.Contains(a.Val, id) {
nodeToDetach = n
return true
}
}
}
parent = n
for c := n.FirstChild; c != nil; c = c.NextSibling {
if traverse(c) {
return true
}
}
parent = n.Parent // Reset parent as we backtrack
return false
}
found := traverse(n)
if found && parent != nil && nodeToDetach != nil {
// Detach nodeToDetach from its parent
if nodeToDetach.PrevSibling != nil {
nodeToDetach.PrevSibling.NextSibling = nodeToDetach.NextSibling
} else {
parent.FirstChild = nodeToDetach.NextSibling
}
if nodeToDetach.NextSibling != nil {
nodeToDetach.NextSibling.PrevSibling = nodeToDetach.PrevSibling
}
}
// Start the search and detach process
if nodeToDetach != nil {
return nodeToDetach, true
}
return nil, false
}