mirror of
https://github.com/PuerkitoBio/goquery
synced 2025-10-05 16:56:57 +08:00
make AttrOr return default value if selection is empty
This commit is contained in:
@@ -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.
|
// AttrOr works like Attr but returns default value if attribute is not present.
|
||||||
func (s *Selection) AttrOr(attrName, defaultValue string) string {
|
func (s *Selection) AttrOr(attrName, defaultValue string) string {
|
||||||
if len(s.Nodes) == 0 {
|
if len(s.Nodes) == 0 {
|
||||||
return ""
|
return defaultValue
|
||||||
}
|
}
|
||||||
|
|
||||||
val, exists := getAttributeValue(attrName, s.Nodes[0])
|
val, exists := getAttributeValue(attrName, s.Nodes[0])
|
||||||
|
@@ -20,6 +20,11 @@ func TestAttrOr(t *testing.T) {
|
|||||||
} else {
|
} else {
|
||||||
t.Logf("Value returned for not existing attribute: %v.", val)
|
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) {
|
func TestAttrNotExist(t *testing.T) {
|
||||||
|
Reference in New Issue
Block a user