class Hpricot::Elements

Once you’ve matched a list of elements, you will often need to handle them as a group. Or you may want to perform the same action on each of them. Hpricot::Elements is an extension of Ruby’s array class, with some methods added for altering elements contained in the array.

If you need to create an element array from regular elements:

Hpricot::Elements[ele1, ele2, ele3]

Assuming that ele1, ele2 and ele3 contain element objects (Hpricot::Elem, Hpricot::Doc, etc.)

Continuing Searches

Usually the Hpricot::Elements you’re working on comes from a search you’ve done. Well, you can continue searching the list by using the same at and search methods you can use on plain elements.

elements = doc.search("/div/p")
elements = elements.search("/a[@href='http://hoodwink.d/']")
elements = elements.at("img")

Altering Elements

When you’re altering elements in the list, your changes will be reflected in the document you started searching from.

doc = Hpricot("That's my <b>spoon</b>, Tyler.")
doc.at("b").swap("<i>fork</i>")
doc.to_html
  #=> "That's my <i>fork</i>, Tyler."

Getting More Detailed

If you can’t find a method here that does what you need, you may need to loop through the elements and find a method in Hpricot::Container::Trav which can do what you need.

For example, you may want to search for all the H3 header tags in a document and grab all the tags underneath the header, but not inside the header. A good method for this is next_sibling:

doc.search("h3").each do |h3|
  while ele = h3.next_sibling
    ary << ele   # stuff away all the elements under the h3
  end
end

Most of the useful element methods are in the mixins Hpricot::Traverse and Hpricot::Container::Trav.