diff --git a/property.go b/property.go index 962defa..8aaf0c4 100644 --- a/property.go +++ b/property.go @@ -32,7 +32,10 @@ func (s *Selection) RemoveAttr(attrName string) *Selection { // SetAttr sets the given attribute on each element in the set of matched elements. func (s *Selection) SetAttr(attrName, val string) *Selection { for _, n := range s.Nodes { - if attr := getAttributePtr(attrName, n); attr != nil { + attr := getAttributePtr(attrName, n) + if attr == nil { + n.Attr = append(n.Attr, html.Attribute{Key: attrName, Val: val}) + } else { attr.Val = val } } diff --git a/property_test.go b/property_test.go index 0d12916..38061f0 100644 --- a/property_test.go +++ b/property_test.go @@ -46,6 +46,21 @@ func TestSetAttr(t *testing.T) { } } +func TestSetAttr2(t *testing.T) { + sel := Doc2Clone().Find("#main") + + sel.SetAttr("foo", "bar") + + val, ok := sel.Attr("foo") + if !ok { + t.Error("Expected an 'foo' attribute on main") + } + + if val != "bar" { + t.Errorf("Expected an attribute 'foo' to be 'bar', got '%s'", val) + } +} + func TestText(t *testing.T) { txt := Doc().Find("h1").Text() if strings.Trim(txt, " \n\r\t") != "Provok.in" {