From 23904f680554c2af98b4ccfdb963cd11a5a698ba Mon Sep 17 00:00:00 2001 From: Piotr Kowalczuk Date: Fri, 17 Apr 2015 00:30:41 +0200 Subject: [PATCH 1/2] Selection.AttrOr shorthand method --- property.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/property.go b/property.go index 8aaf0c4..0c41755 100644 --- a/property.go +++ b/property.go @@ -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 { From c416dcdfae16ba6edfce699f7902dfd194268636 Mon Sep 17 00:00:00 2001 From: Piotr Kowalczuk Date: Fri, 17 Apr 2015 00:38:27 +0200 Subject: [PATCH 2/2] Selection.AttrOr test --- property_test.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/property_test.go b/property_test.go index 38061f0..ee6f821 100644 --- a/property_test.go +++ b/property_test.go @@ -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)