module Nokogiri::HTML

def fragment string

Parse a fragment from +string+ in to a NodeSet.
###
def fragment string
  doc = parse(string)
  fragment = XML::DocumentFragment.new(doc)
  finder = lambda { |c, f|
    c.each do |child|
      if string == child.content && child.name == 'text'
        fragment.add_child(child)
      end
      fragment.add_child(child) if string =~ /<#{child.name}/
    end
    return fragment if fragment.children.length > 0
    c.each do |child|
      finder.call(child.children, f)
    end
  }
  finder.call(doc.children, finder)
  fragment
end