"elems is undefined" JavaScript error calling $(this).text() in .replaceWith() argument

"elems is undefined" JavaScript error calling $(this).text() in .replaceWith() argument

I get a JavaScript error, "elems is undefined", when I call $(this).text() in a function which is a .replaceWith() argument, and .replaceWith() is called on an empty set of elements

e.g. assuming the selector '.foo' matches no elements, then I get this "elems is undefined" JavaScript error running the following,

        $('.foo').replaceWith(function ()
          {
            return '<div>' + $(this).text() + '</div>';
          });

Here's a test page which throws this "elems is undefined" error, http://www.sfu.ca/~jdbates/tmp/jquery/201002220/

What am I doing wrong?