I have the following HTML:
<html>
<body>
<h1>Foo</h1>
<p>The quick brown fox.</p>
<h1>Bar</h1>
<p>Jumps over the lazy dog.</p>
</body>
</html>
I'd like to change it into the following HTML:
<html>
<body>
<p class="title">Foo</p>
<p>The quick brown fox.</p>
<p class="title">Bar</p>
<p>Jumps over the lazy dog.</p>
</body>
</html>
How can I find and replace certain HTML tags? I can use the Nokogiri gem.
Try this:
require 'nokogiri'
html_text = "<html><body><h1>Foo</h1><p>The quick brown fox.</p><h1>Bar</h1><p>Jumps over the lazy dog.</p></body></html>"
frag = Nokogiri::HTML(html_text)
frag.xpath("//h1").each { |div| div.name= "p"; div.set_attribute("class" , "title") }