This is a port of the idea behind Perl's HTML::TokeParser::Simple.
For more information, see the README file or just download the source or the installable tarball.