Skip to content Skip to sidebar Skip to footer

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 do

Solution 1:

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

$('#container').html($('#container').html().replace(/(dog)/g,'<span class="highlight">$1</span>'));

Solution 2:

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.

Post a Comment for "Wrap Some Specified Words With Span In Jquery?"