简体   繁体   中英

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

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: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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM