Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hpricot remove single element

Tags:

ruby

hpricot

I'm using Ruby's Hpricot gem to parse html. I'd like to remove a single node from the document for use elsewhere, but I can't find a way.

I see that I can remove an entire list of elements, using an instance of Hpricot::Elements (x = (doc/"div").remove), but I only want to remove the first instance of a given tag.

Poking around, I see the suggestion that I simply replace the element's inner text with a comment node or whitespace (x.inner_html = ''), but that prevents me making use of the node elsewhere.

What can I do?

Specs: Ruby 1.8.7, Hpricot 0.8.4

like image 757
JellicleCat Avatar asked May 10 '26 03:05

JellicleCat


1 Answers

Try this!

x = (doc/"div").first
x.parent.children.delete(x) unless x.nil?
like image 120
Cameron C Avatar answered May 11 '26 19:05

Cameron C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!