add HasClass() method

This commit is contained in:
Martin Angers
2012-08-29 16:15:14 -04:00
parent 424a91ab92
commit de2aae3fa2
2 changed files with 40 additions and 5 deletions
+33 -5
View File
@@ -6,6 +6,7 @@ import (
//"fmt"
"net/http"
"net/url"
"regexp"
"strings"
)
@@ -131,13 +132,12 @@ func (this *Selection) AddFromSelection(sel *Selection) *Selection {
return this
}
// The Attr() method gets the attribute value for only the first element in the Selection.
// To get the value for each element individually, use a looping construct such as Each() or Map() method.
func (this *Selection) Attr(attrName string) (val string, exists bool) {
if this.Nodes == nil || len(this.Nodes) == 0 {
func getAttributeValue(attrName string, n *html.Node) (val string, exists bool) {
if n == nil {
return
}
for _, a := range this.Nodes[0].Attr {
for _, a := range n.Attr {
if a.Key == attrName {
val = a.Val
exists = true
@@ -147,6 +147,15 @@ func (this *Selection) Attr(attrName string) (val string, exists bool) {
return
}
// The Attr() method gets the attribute value for only the first element in the Selection.
// To get the value for each element individually, use a looping construct such as Each() or Map() method.
func (this *Selection) Attr(attrName string) (val string, exists bool) {
if len(this.Nodes) == 0 {
return
}
return getAttributeValue(attrName, this.Nodes[0])
}
// Returns a new Selection object.
func (this *Document) Children() *Selection {
return this.ChildrenFiltered("")
@@ -239,3 +248,22 @@ func (this *Selection) Get(index int) *html.Node {
}
return nil
}
// Returns true if at least one node in the selection has the given class
func (this *Selection) HasClass(class string) bool {
var rx = regexp.MustCompile("[\t\r\n]")
class = " " + class + " "
for _, n := range this.Nodes {
// Applies only to element nodes
if n.Type == html.ElementNode {
if elClass, ok := getAttributeValue("class", n); ok {
elClass = rx.ReplaceAllString(" "+elClass+" ", " ")
if strings.Index(elClass, class) > -1 {
return true
}
}
}
}
return false
}
+7
View File
@@ -198,3 +198,10 @@ func TestGet(t *testing.T) {
t.Error("Expected node to be nil.")
}
}
func TestHasClass(t *testing.T) {
sel := doc.Find("div")
if !sel.HasClass("span12") {
t.Error("Expected at least one div to have class span12.")
}
}