# Find all possible container nodes of a given text

**URL:** <https://www.ruby-forum.com/t/find-all-possible-container-nodes-of-a-given-text/79961>\
**Category:** Ruby\
**Created:** [December 20, 2006, 7:14pm UTC](https://www.ruby-forum.com/t/find-all-possible-container-nodes-of-a-given-text/79961 "2006-12-20T19:14:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sylvain\_T](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/49beb7/32.png) [@Sylvain\_T](https://www.ruby-forum.com/u/Sylvain_T)\
**Post date:** [December 20, 2006, 7:14pm UTC](https://www.ruby-forum.com/t/find-all-possible-container-nodes-of-a-given-text/79961/1 "2006-12-20T19:14:25Z")

</div>

hi,  
I’ve been using ruby for a few weeks and been messing with DOM-like  
programming  
using hpricot.  
I’m looking for an efficient (rubyiish) way to find the set of Node  
Elements  
that have a text\_element child containing a given string

for instance given the html code

| harr is a dog | fuu is a cat | jii is a dog |

I would like to set this query

getNodesContaining(“dog”)

that would return an Array with the xpath of the first and third td  
(since they  
contain the text dog)

thanks in advance

Sylvain

---

<div class="post-metadata">

**Author:** ![Sylvain\_T](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/49beb7/32.png) [@Sylvain\_T](https://www.ruby-forum.com/u/Sylvain_T)\
**Post date:** [December 20, 2006, 7:22pm UTC](https://www.ruby-forum.com/t/find-all-possible-container-nodes-of-a-given-text/79961/2 "2006-12-20T19:22:52Z")

</div>

well I think I solved it

#!/usr/bin/ruby  
require ‘hpricot’

html = \<\<EOS

| harr is a dog | fuu is a cat | jii is adog |

EOS

doc = Hpricot(html)  
result=[]  
doc.traverse\_text do |text|  
text\_out = text.to\_s.strip  
if text\_out =~ /dog/  
result \<\< text.parent.xpath  
end  
end

thanks anyway

Sylvain

Selon Sylvain T. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

---

<div class="post-metadata">

**Author:** ![Sylvain\_T](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/49beb7/32.png) [@Sylvain\_T](https://www.ruby-forum.com/u/Sylvain_T)\
**Post date:** [December 20, 2006, 7:29pm UTC](https://www.ruby-forum.com/t/find-all-possible-container-nodes-of-a-given-text/79961/3 "2006-12-20T19:29:03Z")

</div>

> > I would like to set this query
> > 
> > getNodesContaining(“dog”)

(Hpricot(html)/“//td”).map.reject{ |node| node.inner\_text !~ /dog/ }

Cheers,  
Peter

\_\_  
[http://www.rubyrailways.com](http://www.rubyrailways.com)
