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

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

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


Another approach, split by keyword and join with the updated html.

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

Note: I haven't tested this, but I'm assuming this would perform worse than doing a replace, but figure I would include anyways for informative purposes


Here is a variation on @undefined's answer, which loops through an array of items:

var barnyardArray = [
    'cow',
    'horse',
    'chicken',
    'hog',
    'goat',
    'goose',
    'duck',
    'llama'
];

$.each(barnyardArray, function (index, value) {
    $("p:contains(" + value + ")").html(function (_, html) {
        var regex = new RegExp(value, 'g');
        return html.replace(regex, '<span class="smallcaps">' + value + '</span>');
    });
});