# How to delete a node with Hpricot?

**URL:** <https://www.ruby-forum.com/t/how-to-delete-a-node-with-hpricot/104682>\
**Category:** Ruby\
**Created:** [May 21, 2007, 2:04pm UTC](https://www.ruby-forum.com/t/how-to-delete-a-node-with-hpricot/104682 "2007-05-21T14:04:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![liquid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/47e85d/32.png) [@liquid](https://www.ruby-forum.com/u/liquid)\
**Post date:** [May 21, 2007, 2:04pm UTC](https://www.ruby-forum.com/t/how-to-delete-a-node-with-hpricot/104682/1 "2007-05-21T14:04:49Z")

</div>

Hi,

Sorry if this is not the right forum for this question.

If a node is bad I’m trying to comment it out. If it’s really bad  
I’m trynig to delete it.

The way I’m trying to do is is as follows.

def this\_is\_a\_problem  
doc = Hpricot( html )  
doc.traverse\_element do |node|  
if some\_bad\_node\_test  
unless really\_bad?  
node.swap( “” )  
else  
node.swap( “” )  
end  
end  
doc.to\_html  
end

However I’m getting a nasty error.

TypeError: no implicit conversion from nil to integer  
/usr/local/lib/ruby/gems/1.8/gems/hpricot-0.5/lib/hpricot/traverse.rb:395:in  
`[]=’

Am I doing this the wrong way?

Thanx

Daniel

---

<div class="post-metadata">

**Author:** ![liquid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/47e85d/32.png) [@liquid](https://www.ruby-forum.com/u/liquid)\
**Post date:** [May 22, 2007, 4:36am UTC](https://www.ruby-forum.com/t/how-to-delete-a-node-with-hpricot/104682/2 "2007-05-22T04:36:49Z")

</div>

I can’t comment on the error, but you can delete a given node in your  
traverse\_element block by doing node.parent.children.delete(node).

Alternatively, you can run a search first to remove the “really bad  
elements.” If you define really bad elements in terms of an xpath  
query, this becomes very simple:

(doc/“script”).remove

Then you can go through and swap things out as necessary:

(doc/“xpath to bad nodes”).each do |el|  
el.inner\_html = “”  
end

---

<div class="post-metadata">

**Author:** ![liquid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/47e85d/32.png) [@liquid](https://www.ruby-forum.com/u/liquid)\
**Post date:** [May 22, 2007, 5:10am UTC](https://www.ruby-forum.com/t/how-to-delete-a-node-with-hpricot/104682/3 "2007-05-22T05:10:51Z")

</div>

On 5/22/07, eden li [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> > I’m trynig to delete it.  
> > node.swap( “” )
> > 
> > Am I doing this the wrong way?
> > 
> > Thanx
> > 
> > Daniel

Sweet, that looks like a good way to go. I’ll try that out.

I’ve actually got it working but it’s very very slow, hopefully this  
will speed it up

Thankyou  
Daniel
