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?
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>
# ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With