title: How to navigate the DOM using Nokogiri
body: <p>I'm trying to fill the variables <code>parent_element_h1</code> and <code>parent_element_h2</code>. Can anyone help me use <a href="http://github.com/tenderlove/nokogiri/tree/master" rel="nofollow noreferrer">Nokogiri</a> to get the information I need into those variables? </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;h1&gt;Foo&lt;/h1&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;h2&gt;Bar&lt;/h2&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;/body&gt;
    &lt;/html&gt;"
  HTML_END
  
  parent = value.css('body').first
  
  # start_here is given: A Nokogiri::XML::Element of the &lt;div&gt; with the id 'X2
  start_here = parent.at('div.block#X2')
  
  # this should be a Nokogiri::XML::Element of the nearest, previous h1.
  # in this example it's the one with the value 'Foo'
  parent_element_h1 = 
  
  # this should be a Nokogiri::XML::Element of the nearest, previous h2. 
  # in this example it's the one with the value 'Bar'
  parent_element_h2 =
  </code></pre>
  
  <hr>
  
  <p>Please note: The <code>start_here</code> element could be anywhere inside the document. The HTML data is just an example. That said, the headers <code>&lt;h1&gt;</code> and <code>&lt;h2&gt;</code> could be a sibling of <code>start_here</code> or a child of a sibling of <code>start_here</code>.</p>
  
  <p>The following recursive method is a good starting point, but it doesn't work on <code>&lt;h1&gt;</code> because it's a child of a sibling of <code>start_here</code>:</p>
  
  <pre><code>def search_element(_block,_style)
    unless _block.nil?
      if _block.name == _style
        return _block
      else
        search_element(_block.previous,_style)
      end
    else
      return false
    end
  end
  
  parent_element_h1 = search_element(start_here,'h1')
  parent_element_h2 = search_element(start_here,'h2')
  </code></pre>
  
  <hr>
  
  <p>After accepting an answer, I came up with <a href="https://stackoverflow.com/a/778182/30594">my own solution</a>. It works like a charm and I think it's pretty cool.</p>