-->

Find a string of text in an element and wrap some

2019-01-01 16:07发布

问题:

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

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.

回答1:

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

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



回答2:

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



回答3:

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>\');
    });
});


回答4:

$(\"h2:contains(\'cow\')\").each(function() {
    var newText = $(this).html().replace(\"cow\", \"<span class=\'smallcaps\'></span>\");
    $(this).html(newText);
});


回答5:

In my case i have some tag inside the target div and some text i need to wrap that text into a link.

This how i did following \"What have you tried\".

var oldText = $(this).text(),
newText = $(this).html().replace(
    oldText, 
    \"<a class=\'k-link\' href=\'#\' class=\'smallcaps\'>\" + 
        oldText + 
    \"<span class=\'k-icon k-i-arrow-n\'></span></a>\"
);
$(this).html(newText);