Skip to content

Operating on node attributes #666

Description

@zzak

From the docs: A Nokogiri::XML::Node may be treated similarly to a hash with regard to attributes

I want to prepend a regular hash attribute

my_hash = { 'my_key' => 'bar' }
my_hash['my_key'].insert 0, 'foo'
my_hash #=> {'my_key'=>'foobar'}

This simply cannot be done with nokogiri

doc = Nokogiri::HTML('<img src="bar" />')
doc.xpath("//img").each { |img| img['src'].insert 0, 'foo' }
doc.to_html #=> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><img src=\"bar\"></body></html>\n"

You can do this if you get(attribute) first, however

doc.xpath("//img").each { |img| _src = img['src']; img['src'] = _src.insert 0, 'foo' }
doc.to_html #=> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><img src=\"foobar\"></body></html>\n"

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions