mirror of
https://github.com/PuerkitoBio/goquery
synced 2025-10-05 08:46:53 +08:00
manipulation: Add Remove*() functions.
This commit is contained in:
@@ -130,3 +130,27 @@ func (s *Selection) Clone() *Selection {
|
||||
ns.Nodes = cloneNodes(s.Nodes)
|
||||
return ns
|
||||
}
|
||||
|
||||
// Remove the set of matched elements from the document.
|
||||
// Returns the same selection, now consisting of nodes not in the document.
|
||||
func (s *Selection) Remove() *Selection {
|
||||
for _, n := range s.Nodes {
|
||||
if n.Parent != nil {
|
||||
n.Parent.RemoveChild(n)
|
||||
}
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// Filter the set of matched elements by selector before removing.
|
||||
// Returns the filtered Selection.
|
||||
func (s *Selection) RemoveFilter(selector string) *Selection {
|
||||
return s.RemoveFilterSelector(cascadia.MustCompile(selector))
|
||||
}
|
||||
|
||||
// Filter the set of matched elements by cascadia selector before removing.
|
||||
// Returns the filtered Selection.
|
||||
func (s *Selection) RemoveFilterSelector(cs cascadia.Selector) *Selection {
|
||||
return s.FilterSelector(cs).Remove()
|
||||
}
|
||||
|
@@ -45,3 +45,36 @@ func TestAppendHtml(t *testing.T) {
|
||||
|
||||
AssertLength(t, doc.Find("strong").Nodes, 14)
|
||||
}
|
||||
|
||||
func TestRemove(t *testing.T) {
|
||||
doc := Doc2Clone()
|
||||
doc.Find("#nf1").Remove()
|
||||
|
||||
AssertLength(t, doc.Find("#foot #nf1").Nodes, 0)
|
||||
}
|
||||
|
||||
func TestRemoveAll(t *testing.T) {
|
||||
doc := Doc2Clone()
|
||||
doc.Find("*").Remove()
|
||||
|
||||
AssertLength(t, doc.Find("*").Nodes, 0)
|
||||
}
|
||||
|
||||
func TestRemoveRoot(t *testing.T) {
|
||||
doc := Doc2Clone()
|
||||
doc.Find("html").Remove()
|
||||
|
||||
AssertLength(t, doc.Find("html").Nodes, 0)
|
||||
}
|
||||
|
||||
func TestRemoveFilter(t *testing.T) {
|
||||
doc := Doc2Clone()
|
||||
nf6 := doc.Find("#nf6")
|
||||
s := doc.Find("div").RemoveFilter("#nf6")
|
||||
|
||||
AssertLength(t, doc.Find("#nf6").Nodes, 0)
|
||||
AssertLength(t, s.Nodes, 1)
|
||||
if nf6.Nodes[0] != s.Nodes[0] {
|
||||
t.Error("Removed node does not match original")
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user