Note that there are some explanatory texts on larger screens.

plurals
  1. PONokogiri: Select content between element A and B
    primarykey
    data
    text
    <p>What's the smartest way to have Nokogiri select all content between the start and the stop element (including start-/stop-element)?</p> <p>Check example code below to understand what I'm looking for:</p> <pre><code>require 'rubygems' require 'nokogiri' value = Nokogiri::HTML.parse(&lt;&lt;-HTML_END) "&lt;html&gt; &lt;body&gt; &lt;p id='para-1'&gt;A&lt;/p&gt; &lt;div class='block' id='X1'&gt; &lt;p class="this"&gt;Foo&lt;/p&gt; &lt;p id='para-2'&gt;B&lt;/p&gt; &lt;/div&gt; &lt;p id='para-3'&gt;C&lt;/p&gt; &lt;p class="that"&gt;Bar&lt;/p&gt; &lt;p id='para-4'&gt;D&lt;/p&gt; &lt;p id='para-5'&gt;E&lt;/p&gt; &lt;div class='block' id='X2'&gt; &lt;p id='para-6'&gt;F&lt;/p&gt; &lt;/div&gt; &lt;p id='para-7'&gt;F&lt;/p&gt; &lt;p id='para-8'&gt;G&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;" HTML_END parent = value.css('body').first # START element @start_element = parent.at('p#para-3') # STOP element @end_element = parent.at('p#para-7') </code></pre> <p><strong>The result (return value) should look like this</strong>:</p> <pre><code>&lt;p id='para-3'&gt;C&lt;/p&gt; &lt;p class="that"&gt;Bar&lt;/p&gt; &lt;p id='para-4'&gt;D&lt;/p&gt; &lt;p id='para-5'&gt;E&lt;/p&gt; &lt;div class='block' id='X2'&gt; &lt;p id='para-6'&gt;F&lt;/p&gt; &lt;/div&gt; &lt;p id='para-7'&gt;F&lt;/p&gt; </code></pre> <p><strong>Update: This is my current solution, though I think there must be something smarter:</strong></p> <pre><code>@my_content = "" @selected_node = true def collect_content(_start) if _start == @end_element @my_content &lt;&lt; _start.to_html @selected_node = false end if @selected_node == true @my_content &lt;&lt; _start.to_html collect_content(_start.next) end end collect_content(@start_element) puts @my_content </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload