Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap some specified words with span in jQuery?

I'd like to know the most convenient way to wrap some specified words with span-tags.

Example: I have a word, which is dog. Here's the original text:

I have a dog, do you have a dog?

And output should be like this:

I have a <span class="highlight">dog</span>, do you have a <span class="highlight">dog</span>?

Any help?

EDIT: Note, that it should also wrap words, even if they are not invidual (Peter-dog). Hope you got it.

like image 371
Martti Laine Avatar asked Feb 06 '10 21:02

Martti Laine


2 Answers

You can use the JavaScript replace function. Here is a basic example:

$('#container').html($('#container').html().replace(/(dog)/g,'<span class="highlight">$1</span>'));
like image 154
Chris Bartow Avatar answered Nov 16 '22 20:11

Chris Bartow


Here's a useful jQuery plugin.

It's really easy to use and it works great.

edit — this is a very old answer of mine. I regret having simply linked the Lettering.js library without including its name. The library is useful, though I'm not sure here 7 years later whether Mr. Rupert continues to actively maintain it.

What Lettering does is go through the text nodes in a selected region of the DOM and wrap the individual letters and/or words (configurable) in <span> tags that can then be styled. It's simple but effective. Even if you don't want to use it, the code is not very extensive and it's instructional.

like image 23
Pointy Avatar answered Nov 16 '22 19:11

Pointy