github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/goquery/property.go (about) 1 package goquery 2 3 import ( 4 "bytes" 5 "code.google.com/p/go.net/html" 6 ) 7 8 // Attr() gets the specified attribute's value for the first element in the 9 // Selection. To get the value for each element individually, use a looping 10 // construct such as Each() or Map() method. 11 func (this *Selection) Attr(attrName string) (val string, exists bool) { 12 if len(this.Nodes) == 0 { 13 return 14 } 15 return getAttributeValue(attrName, this.Nodes[0]) 16 } 17 18 // Text() gets the combined text contents of each element in the set of matched 19 // elements, including their descendants. 20 func (this *Selection) Text() string { 21 var buf bytes.Buffer 22 23 // Slightly optimized vs calling Each(): no single selection object created 24 for _, n := range this.Nodes { 25 buf.WriteString(getNodeText(n)) 26 } 27 return buf.String() 28 } 29 30 // Size() is an alias for Length(). 31 func (this *Selection) Size() int { 32 return this.Length() 33 } 34 35 // Length() returns the number of elements in the Selection object. 36 func (this *Selection) Length() int { 37 return len(this.Nodes) 38 } 39 40 // Html() gets the HTML contents of the first element in the set of matched 41 // elements. It includes text and comment nodes. 42 func (this *Selection) Html() (ret string, e error) { 43 // Since there is no .innerHtml, the HTML content must be re-created from 44 // the nodes usint html.Render(). 45 var buf bytes.Buffer 46 47 if len(this.Nodes) > 0 { 48 for c := this.Nodes[0].FirstChild; c != nil; c = c.NextSibling { 49 e = html.Render(&buf, c) 50 if e != nil { 51 return 52 } 53 } 54 ret = buf.String() 55 } 56 57 return 58 } 59 60 // Get the specified node's text content. 61 func getNodeText(node *html.Node) string { 62 if node.Type == html.TextNode { 63 // Keep newlines and spaces, like jQuery 64 return node.Data 65 } else if node.FirstChild != nil { 66 var buf bytes.Buffer 67 for c := node.FirstChild; c != nil; c = c.NextSibling { 68 buf.WriteString(getNodeText(c)) 69 } 70 return buf.String() 71 } 72 73 return "" 74 } 75 76 // Private function to get the specified attribute's value from a node. 77 func getAttributeValue(attrName string, n *html.Node) (val string, exists bool) { 78 if n == nil { 79 return 80 } 81 82 for _, a := range n.Attr { 83 if a.Key == attrName { 84 val = a.Val 85 exists = true 86 return 87 } 88 } 89 return 90 }