Jquery – Find a string of text in an element and wrap some span tags round it

jquerystringtext;

I want to find a string of text in an element and wrap some span tags round it. E.g.

From:

<h2>We have cows on our farm</h2>

To:

<h2>We have <span class='smallcaps'>cows</span> on our farm</h2>

I've tried:

$("h2:contains('cow')").each(function() {
 $(this).text().wrap("<span class='smallcaps'></span>");
});

But that only wraps the whole containing h2 tag.

Best Answer

$("h2:contains('cow')").html(function(_, html) {
   return html.replace(/(cow)/g, '<span class="smallcaps">$1</span>');
});

http://jsfiddle.net/w5ze6/1/