mirror of
https://github.com/PuerkitoBio/goquery.git
synced 2024-04-21 12:31:36 +00:00
add Get() method
This commit is contained in:
+23
@@ -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
|
||||
}
|
||||
|
||||
@@ -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.")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user