Method: Nokogiri::XML::NodeSet#attr
- Defined in:
- lib/nokogiri/xml/node_set.rb
#attr(key, value = nil, &block) ⇒ Object Also known as: set, attribute
Set attributes on each Node in the NodeSet, or get an attribute from the first Node in the NodeSet.
To get an attribute from the first Node in a NodeSet:
node_set.attr("href") # => "https://www.nokogiri.org"
Note that an empty NodeSet will return nil when #attr
is called as a getter.
To set an attribute on each node, key
can either be an attribute name, or a Hash of attribute names and values. When called as a setter, #attr
returns the NodeSet.
If key
is an attribute name, then either value
or block
must be passed.
If key
is a Hash then attributes will be set for each key/value pair:
node_set.attr("href" => "https://www.nokogiri.org", "class" => "member")
If value
is passed, it will be used as the attribute value for all nodes:
node_set.attr("href", "https://www.nokogiri.org")
If block
is passed, it will be called on each Node object in the NodeSet and the return value used as the attribute value for that node:
node_set.attr("class") { |node| node.name }
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
# File 'lib/nokogiri/xml/node_set.rb', line 205 def attr(key, value = nil, &block) unless key.is_a?(Hash) || (key && (value || block)) return first&.attribute(key) end hash = key.is_a?(Hash) ? key : { key => value } hash.each do |k, v| each do |node| node[k] = v || yield(node) end end self end |