Get parent element from HTML using Nokogiri
Asked Answered
P

1

8

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?

Proselyte answered 19/3, 2015 at 7:35 Comment(9)
If you add some classes on parent nodes then you can try doc.xpath('//p[@class="parent"]/text()')Epiphragm
hey its returning empty arrayProselyte
or you can also try doc.css('p').children.remove then will remove children and will give you parent nodeEpiphragm
@DeeptiKakade the above html doesn't looks valid. Are you sure you pasted correct codeBernardo
@DeeptiKakade - Play around with doc.xpath('//p')Epiphragm
doc = Nokogiri::HTML::DocumentFragment.parse('j_text') doc.at('p')Epiphragm
@ParitoshPiplewar actually I have extracted this string from html and I want a parent tags in the document. I don't want only <p> tagProselyte
@ParitoshPiplewar I just want to extract a parent element from the above exampleProselyte
The elements in your HTML document fragment have no parent.Acrimony
A
12

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>
#   ...
Acrimony answered 19/3, 2015 at 23:1 Comment(1)
I did with doc = Nokogiri::HTML(j_text).css('body').childrenProselyte

© 2022 - 2024 — McMap. All rights reserved.