Find a string of text in an element and wrap some

2019-01-01 16:13发布

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.

5条回答
骚的不知所云
2楼-- · 2019-01-01 16:19

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楼-- · 2019-01-01 16:33

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楼-- · 2019-01-01 16:38
$("h2:contains('cow')").html(function(_, html) {
   return html.replace(/(cow)/g, '<span class="smallcaps">$1</span>');
});

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

查看更多
骚的不知所云
5楼-- · 2019-01-01 16:41

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);
查看更多
牵手、夕阳
6楼-- · 2019-01-01 16:42
$("h2:contains('cow')").each(function() {
    var newText = $(this).html().replace("cow", "<span class='smallcaps'></span>");
    $(this).html(newText);
});
查看更多
登录 后发表回答