public Method

Elements.attr(key, value = nil, &blk)

Gets and sets attributes on all matched elements.

Pass in a key on its own and this method will return the string value assigned to that attribute for the first elements. Or nil if the attribute isn’t found.

doc.search("a").attr("href")
  #=> "http://hacketyhack.net/"

Or, pass in a key and value. This will set an attribute for all matched elements.

doc.search("p").attr("class", "basic")

You may also use a Hash to set a series of attributes:

(doc/"a").attr(:class => "basic", :href => "http://hackety.org/")

Lastly, a block can be used to rewrite an attribute based on the element it belongs to. The block will pass in an element. Return from the block the new value of the attribute.

records.attr("href") { |e| e['href'] + "#top" }

This example adds a #top anchor to each link.

Source Code

# File hpricot/elements.rb, line 201
def attr key, value = nil, &blk
  if value or blk
    each do |el|
      el.set_attribute(key, value || blk[el])
    end
    return self      
  end    
  if key.is_a? Hash
    key.each { |k,v| self.attr(k,v) }
    return self
  else
    return self[0].get_attribute(key)
  end
end
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.