1

I have a script to wrap html tags around the selection.

function wrap(tagName)
{
var selection;
var elements = [];
var ranges = [];
var rangeCount = 0;

if (window.getSelection)
{
    selection = window.getSelection();
    if (selection.rangeCount)
    {
        rangeCount = selection.rangeCount;
        for (var i=0; i<rangeCount; i++)
        {
            ranges[i] = selection.getRangeAt(i).cloneRange();
            elements[i] = document.createElement(tagName);
            elements[i].appendChild(ranges[i].cloneContents());
            ranges[i].deleteContents();
            ranges[i].insertNode(elements[i]);
            ranges[i].selectNode(elements[i]);
        }
        selection.removeAllRanges();
        for (var i=0; i<ranges.length; i++)
        {
            selection.addRange(ranges[i]);
        }
    }
}
}

It works fine, but when I try to select the following text and wrap tags around the following code

<strong>W</strong>elcom<strong>e</strong>

The code changes to

<strong></strong><u><strong>W</strong>elcom<strong>e</strong></u><strong></strong>

instead of

<u><strong>W</strong>elcom<strong>e</strong></u>

I have inspected the code with firebug and it goes wrong at the function deleteContents(). The function deleteContents() leaves two empty nodes <strong></strong> so it doesn't delete the whole content. How does this happen?

4

0 回答 0