make AttrOr return default value if selection is empty

This commit is contained in:
Martin Angers
2015-06-05 22:16:32 -04:00
parent 60ec77b003
commit b4440419d8
2 changed files with 6 additions and 1 deletions

View File

@@ -23,7 +23,7 @@ func (s *Selection) Attr(attrName string) (val string, exists bool) {
// 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 ""
return defaultValue
}
val, exists := getAttributeValue(attrName, s.Nodes[0])

View File

@@ -20,6 +20,11 @@ func TestAttrOr(t *testing.T) {
} else {
t.Logf("Value returned for not existing attribute: %v.", val)
}
if val := Doc().Find("zz").AttrOr("fake-attribute", "alternative"); val != "alternative" {
t.Error("Expected an alternative value for 'fake-attribute' on an empty selection.")
} else {
t.Logf("Value returned for empty selection: %v.", val)
}
}
func TestAttrNotExist(t *testing.T) {