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.
You can use the JavaScript replace function. Here is a basic example:
$('#container').html($('#container').html().replace(/(dog)/g,'<span class="highlight">$1</span>'));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With