开发者

How to grab a word or character and wrap it in a span tag?

开发者 https://www.devze.com 2023-01-30 16:54 出处:网络
I\'m trying to find a particular character in a div and wrap it in a span tag. I thought I could use something like:

I'm trying to find a particular character in a div and wrap it in a span tag.

I thought I could use something like:

$('.breadcrumb开发者_JS百科:contains("»")').replaceWith('<span>»</span>');

But this changes the whole breadcrumb div.

What am I doing wrong?


.replaceWith only works on nodes. You need the string method .replace() instead:

var $bc = $('.breadcrumb');
$bc.html($bc.text().replace('»', '<span>»</span>'));

Like Mr. Craver suggested, you can also call:

$bc.html(function(i, html) {
    return html.replace('»', '<span>»</span>');
});

Example: http://www.jsfiddle.net/jwJKr/


var $bc = $('.breadcrumb');
$bc.html($bc.text().split('»').join('<span>»</span>'));

Works better to replace all characters.

0

精彩评论

暂无评论...
验证码 换一张
取 消