I’d like to figure out a way to get to the HTML result (mentioned further below) by using the following Ruby code and Nokogiri:
require 'rubygems' require 'nokogiri' value = Nokogiri::HTML.parse(<<-HTML_END) '<html> <body> <p id='1'>A</p> <p id='2'>B</p> <h1>Bla</h1> <p id='3'>C</p> <p id='4'>D</p> <p id='5'>E</p> </body> </html>' HTML_END # The selected-array is given by the application. # It consists of a sorted array with all ids of # <p> that need to be enclosed by the <div> selected = ['2','3','4'] first_p = selected.first last_p = selected.last # # WHAT RUBY CODE DO I NEED TO INSERT HERE TO GET # THE RESULTING HTML AS SEEN BELOW? #
The resulting HTML should look like this (please note the inserted <div id='XYZ'>):
<html> <body> <p id='1'>A</p> <div id='XYZ'> <p id='2'>B</p> <h1>Bla</h1> <p id='3'>C</p> <p id='4'>D</p> </div> <p id='5'>E</p> </body> </html>
This is the working solution I’ve implemented into my project (Vlad@SO & Whitelist@irc#rubyonrails: Thanks for your help and inspiration.):