views:

681

answers:

1

I have markup like this:

<p>one two three four</p>

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

<p>one <span>two three<span> four</p>

I have the offset and length of the section I want to wrap in a span, in this case offset = 4 and length = 9. If using jQuery can make it easier, that is preferable.

+2  A: 

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)
    {
        return this.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);
VonC