Adi
Adi

Reputation: 4022

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?

Upvotes: 1

Views: 5032

Answers (2)

Johan B
Johan B

Reputation: 1976

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

Works better to replace all characters.

Upvotes: 2

jAndy
jAndy

Reputation: 235962

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

Upvotes: 3

Related Questions