add Get() method

This commit is contained in:
Martin Angers
2012-08-29 15:13:54 -04:00
parent 08bc32a9b8
commit 920ea7ffb6
2 changed files with 53 additions and 0 deletions
+23
View File
@@ -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
}
+30
View File
@@ -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.")
}
}