Stephan Stephan - 3 months ago 25
Ruby Question

Nokogiri strip all attributes

I have this html markup:

<div class="item"><a href="www"></a></div>


and I'd like to get this:

<div><a></a></div>


How can I do it with Nokogiri?

Answer
require 'nokogiri'
doc = Nokogiri::HTML('<div class="item"><a href="www"></a></div>')
  1. You could remove all attributes by xpath:

    doc.xpath('//@*').remove
    
  2. Or, if you ever need to do something more complex, sometimes it's easier to traverse all elements with:

    doc.traverse do |node| 
      node.keys.each do |attribute|
        node.delete attribute
      end
    end
    
Comments