I'm trying to get the <p>
tag's parent class name?
<div class="entry-content">
<p>Some text...</p>
</div>
How can I obtain this?
Some find that using css and the nokogiri parent
method are easier to read/maintain than xpath:
html = %q{
<div class="entry-content">
<p>Some text...</p>
</div>
}
doc = Nokogiri::HTML(html)
doc.css('p').each do |p|
puts p.parent.attr('class')
end
Use an XPath like //p/..
or //*[p]
(the parent of any "p" element at any depth).
str =<<__HERE__
<div class="entry-content">
<p>Some text...</p>
</div>
__HERE__
html = Nokogiri::HTML(str)
p_parents = html.xpath('//p/..') # => NodeSet containing the "<div>" element.
p_parents.each do |node|
puts node.attr('class') # => "entry-content"
end
I would use #at_css
,instead of css
.
require 'nokogiri'
str =<<__HERE__
<div class="entry-content">
<p>Some text...</p>
</div>
__HERE__
html = Nokogiri::HTML(str)
p_parent = html.at_css('p').parent
p_parent.name # => "div"
p_parent['class'] # => "entry-content"
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