mirror of
https://github.com/PuerkitoBio/goquery.git
synced 2024-04-21 12:31:36 +00:00
SetAttr now creates attributes, in addition to updating attributes, closes #57
This commit is contained in:
+4
-1
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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" {
|
||||
|
||||
Reference in New Issue
Block a user