From 755fd592bb87d0a40b29a982953edbd321c834f4 Mon Sep 17 00:00:00 2001 From: Gleb Tv Date: Wed, 8 Feb 2017 16:27:36 +0300 Subject: [PATCH] implement SetHtml and SetText, fixes #123 --- manipulation.go | 23 +++++++++++++++++++++++ manipulation_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/manipulation.go b/manipulation.go index 3602a5a..8edb4e9 100644 --- a/manipulation.go +++ b/manipulation.go @@ -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. diff --git a/manipulation_test.go b/manipulation_test.go index f1c6e3e..b0f7446 100644 --- a/manipulation_test.go +++ b/manipulation_test.go @@ -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("
test
") + + 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 := "
test
" + 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"))