- Find the desired div.
- Find the stop item you want, and then find all of the following siblings.
- Remove them.
For instance:
<body> <div id="a"> <h2>My Section</h2> <p class="backtotop">Back to Top</p> <p>More Content</p> <p>Even More Content</p> </div> </body>
require 'nokogiri' doc = Nokogiri::HTML(my_html) div = doc.at('#a') div.at('.backtotop').xpath('following-sibling::*').remove puts div
Here's a more complex example where the backtotop element might not be in the root of the div:
<body> <div id="b"> <h2>Another Section</h2> <section> <p class="backtotop">Back to Top</p> <p>More Content</p> </section> <p>Even More Content</p> </div> </body>
require 'nokogiri' doc = Nokogiri::HTML(my_html) div = doc.at('#b') n = div.at('.backtotop') until n==div n.xpath('following-sibling::*').remove n = n.parent end puts div
If your HTML is more complex than the above, please indicate the actual sample along with the desired result. This is good advice for any future question you ask.
source share