From 920ea7ffb6be0f72bc7ce3907edf55251dc0e5db Mon Sep 17 00:00:00 2001 From: Martin Angers Date: Wed, 29 Aug 2012 15:13:54 -0400 Subject: [PATCH] add Get() method --- goquery.go | 23 +++++++++++++++++++++++ goquery_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/goquery.go b/goquery.go index f8e6b8b..7ebae21 100644 --- a/goquery.go +++ b/goquery.go @@ -18,6 +18,8 @@ import ( // - Contents() (similar to Children(), but includes text and comment nodes, so Children() should filter them out) // - End() // - Eq() +// - Find() : Complete with Selection object and Node object as selectors +// - Has() type Document struct { Root *html.Node @@ -224,3 +226,24 @@ func (this *Selection) FilterSelection(s *Selection) *Selection { } return &Selection{matches, this.document} } + +// Returns a new Selection object +func (this *Selection) First() *Selection { + if len(this.Nodes) == 0 { + return &Selection{nil, this.document} + } + return &Selection{[]*html.Node{this.Nodes[0]}, this.document} +} + +// Get() without parameter is not implemented, its behaviour would be exactly the same as getting selection.Nodes +func (this *Selection) Get(index int) *html.Node { + var l = len(this.Nodes) + + if index < 0 { + index += l // Negative index gets from the end + } + if index >= 0 && index < l { + return this.Nodes[index] + } + return nil +} diff --git a/goquery_test.go b/goquery_test.go index e277397..06c52f4 100644 --- a/goquery_test.go +++ b/goquery_test.go @@ -168,3 +168,33 @@ func TestFilterSelection(t *testing.T) { t.Errorf("Expected 1 node, found %v.", len(sel3.Nodes)) } } + +func TestFirst(t *testing.T) { + sel := doc.Find(".pvk-content").First() + if len(sel.Nodes) != 1 { + t.Errorf("Expected 1 node, found %v.", len(sel.Nodes)) + } +} + +func TestFirstEmpty(t *testing.T) { + sel := doc.Find(".pvk-zzcontentzz").First() + if len(sel.Nodes) != 0 { + t.Errorf("Expected 0 node, found %v.", len(sel.Nodes)) + } +} + +func TestGet(t *testing.T) { + sel := doc.Find(".pvk-content") + node := sel.Get(1) + if sel.Nodes[1] != node { + t.Errorf("Expected node %v to be %v.", node, sel.Nodes[1]) + } + node = sel.Get(-3) + if sel.Nodes[0] != node { + t.Errorf("Expected node %v to be %v.", node, sel.Nodes[0]) + } + node = sel.Get(129) + if node != nil { + t.Error("Expected node to be nil.") + } +}