Removing <p> elements without text using Nokogiri
I would start with a method like this (feel free to monkeypatch Nokogiri::XML::Node if you want)
def is_blank?(node) (node.text? && node.content.strip == '') || (node.element? && node.name == 'br') end Then move on to another method that checks that all children are empty:
def all_children_are_blank?(node) node.children.all?{|child| is_blank?(child) } # Here you see the convenience of monkeypatching... sometimes. end And finally get document and
document.css('p').find_all{|p| all_children_are_blank?(p) }.each do |p| p.remove end This is a simpler fix: it removes both spaces and br tags.
given HTML
"<p> </p><p>Foo<p/><p><br/> <br> </p>" Decision:
document.css('p').find_all.each do |p| # Ruby on Rails Solution: p.remove if p.content.blank? # Ruby solution, as pointed out by Michael Hartl: p.remove if p.content.strip.empty? end # document => <p>Foo</p> There's a more elegant way:
require "nokogiri" doc = Nokogiri::HTML.parse <<-EOHTML <div> <p class="empty_p"></p> <p class="full_p">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </div> EOHTML # Magic happens here... doc.at_css("p:first-child:empty").remove puts doc.to_html