Skip to content Skip to sidebar Skip to footer

How Do I Wrap A Span Around A Section Of Text In Javascript?

I have markup like this:

one two three four

And I want to use javascript to convert it to this:

one two three four

I

Solution 1:

Is this not a little duplicate of the question Highlight a word with jQuery ?

Something like the JQuery search highlight plugin could be helpful

Or, as pointed out in the same question, write your own jquery function: Something like (untested code, feel free to edit):

jQuery.fn.addSpan = function (elName, str, offset, length)
{
    if(this.innerHTML = str)
    {
        returnthis.each(function ()
        {
            this.innerHTML = this.innerHTML.substring(0,offset) + "<span>" + this.innerHTML.substring(offset, offset+length) + "</span>" + this.innerHTML.substring(offset+length));
        });
    }
};

And you would use it like so:

$("p").addSpan("one two three four", 4, 9);

Post a Comment for "How Do I Wrap A Span Around A Section Of Text In Javascript?"