mirror of
https://github.com/PuerkitoBio/goquery.git
synced 2026-10-21 03:20:05 +00:00
Merge pull request #73 from piotrkowalczuk/master
Selection.AttrOr shorthand method
This commit is contained in:
+14
@@ -20,6 +20,20 @@ func (s *Selection) Attr(attrName string) (val string, exists bool) {
|
||||
return getAttributeValue(attrName, s.Nodes[0])
|
||||
}
|
||||
|
||||
// AttrOr works like Attr but returns default value if attribute is not present.
|
||||
func (s *Selection) AttrOr(attrName, defaultValue string) string {
|
||||
if len(s.Nodes) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
val, exists := getAttributeValue(attrName, s.Nodes[0])
|
||||
if !exists {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
|
||||
// RemoveAttr removes the named attribute from each element in the set of matched elements.
|
||||
func (s *Selection) RemoveAttr(attrName string) *Selection {
|
||||
for _, n := range s.Nodes {
|
||||
|
||||
@@ -14,6 +14,14 @@ func TestAttrExists(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttrOr(t *testing.T) {
|
||||
if val := Doc().Find("a").AttrOr("fake-attribute", "alternative"); val != "alternative" {
|
||||
t.Error("Expected an alternative value for 'fake-attribute' attribute.")
|
||||
} else {
|
||||
t.Logf("Value returned for not existing attribute: %v.", val)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttrNotExist(t *testing.T) {
|
||||
if val, ok := Doc().Find("div.row-fluid").Attr("href"); ok {
|
||||
t.Errorf("Expected no value for the href attribute, got %v.", val)
|
||||
|
||||
Reference in New Issue
Block a user