mirror of
https://github.com/PuerkitoBio/goquery.git
synced 2024-04-21 12:31:36 +00:00
implement SetHtml and SetText, fixes #123
This commit is contained in:
@@ -270,6 +270,29 @@ func (s *Selection) ReplaceWithNodes(ns ...*html.Node) *Selection {
|
||||
return s.Remove()
|
||||
}
|
||||
|
||||
// Set nodes to specified nodes.
|
||||
func SetNodes(s *Selection, ns ...*html.Node) *Selection {
|
||||
for _, n := range s.Nodes {
|
||||
for c := n.FirstChild; c != nil; c = n.FirstChild {
|
||||
n.RemoveChild(c)
|
||||
}
|
||||
for _, c := range ns {
|
||||
n.AppendChild(cloneNode(c))
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Sets HTML of selected nodes to specified string.
|
||||
func (s *Selection) SetHtml(html string) *Selection {
|
||||
return SetNodes(s, parseHtml(html)...)
|
||||
}
|
||||
|
||||
// Sets text of selected nodes to specified string. Text is HTML escaped
|
||||
func (s *Selection) SetText(text string) *Selection {
|
||||
return s.SetHtml(html.EscapeString(text))
|
||||
}
|
||||
|
||||
// Unwrap removes the parents of the set of matched elements, leaving the matched
|
||||
// elements (and their siblings, if any) in their place.
|
||||
// It returns the original selection.
|
||||
|
||||
@@ -278,6 +278,46 @@ func TestReplaceWithHtml(t *testing.T) {
|
||||
printSel(t, doc.Selection)
|
||||
}
|
||||
|
||||
func TestSetHtml(t *testing.T) {
|
||||
doc := Doc2Clone()
|
||||
q := doc.Find("#main, #foot")
|
||||
q.SetHtml("<div id=\"replace\">test</div>")
|
||||
|
||||
assertLength(t, doc.Find("#replace").Nodes, 2)
|
||||
assertLength(t, doc.Find("#main, #foot").Nodes, 2)
|
||||
|
||||
if q.Text() != "testtest" {
|
||||
t.Errorf("Expected text to be %v, found %v", "testtest", q.Text())
|
||||
}
|
||||
|
||||
printSel(t, doc.Selection)
|
||||
}
|
||||
|
||||
func TestSetText(t *testing.T) {
|
||||
doc := Doc2Clone()
|
||||
q := doc.Find("#main, #foot")
|
||||
repl := "<div id=\"replace\">test</div>"
|
||||
q.SetText(repl)
|
||||
|
||||
assertLength(t, doc.Find("#replace").Nodes, 0)
|
||||
assertLength(t, doc.Find("#main, #foot").Nodes, 2)
|
||||
|
||||
if q.Text() != (repl + repl) {
|
||||
t.Errorf("Expected text to be %v, found %v", (repl + repl), q.Text())
|
||||
}
|
||||
|
||||
h, err := q.Html()
|
||||
if err != nil {
|
||||
t.Errorf("Error: %v", err)
|
||||
}
|
||||
esc := "<div id="replace">test</div>"
|
||||
if h != esc {
|
||||
t.Errorf("Expected html to be %v, found %v", esc, h)
|
||||
}
|
||||
|
||||
printSel(t, doc.Selection)
|
||||
}
|
||||
|
||||
func TestReplaceWithSelection(t *testing.T) {
|
||||
doc := Doc2Clone()
|
||||
sel := doc.Find("#nf6").ReplaceWithSelection(doc.Find("#nf5"))
|
||||
|
||||
Reference in New Issue
Block a user