Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent element from HTML using Nokogiri

Tags:

ruby

nokogiri

I have a following HTML and I want to fetch the parents in the document. I used Nokogiri for parsing:

j_text = "<p>
            <a>abc</a>
            <a>pqr></a>
         </p>
         <table>
           <tr>
             <td><p>example</p></td>
             <td><p>find</p></td>
             <td><p>by</p></td>
             <td><p>ID</p></td>
           </tr>
         </table>
        <p><p>zzzz</p>nnnnn</p>
        <u>sfds<u>"

I did:

doc = Nokogiri::HTML(j_text)

Now I want the parent element from above HTML text i.e <p>, <table>, <p>, <u> using Nokogiri, how do I do this?

like image 480
Deepti Kakade Avatar asked Mar 19 '15 07:03

Deepti Kakade


1 Answers

When you load that HTML fragment in Nokogiri it will automatically insert the elements into a root-level "html" element with a nested "body" element.

As such, the parent of the nodes in the HTML fragment you provided will be the "body":

doc = Nokogiri::HTML(j_text)
doc.root.name # => "html"
doc.xpath('//p').first.parent.name     # => "body"
doc.xpath('//table').first.parent.name # => "body"
doc.xpath('//u').first.parent.name     # => "body"
doc.to_html # =>
# <!DOCTYPE html...
# <html><body>
# <p>
#   <a>abc</a>
#   ...
like image 164
maerics Avatar answered Sep 19 '22 13:09

maerics