Add HTML element after text
<p>I am looking for a way to add an HTML element using JavaScript. But the problem is that the new element might be in between some text. In all other cases I'm using the insertBefore() method.</p>

<p>I am using the following function to get the cursor position. 
My initial approach was to split the target innerHTML and add the necessary tags but the cursor position provided does not take into account the character conversions such as space to <code> &amp;nbsp;</code>. So if there are multiple continous spaces, the cursor position will not give the coreect position int he innerHTML.</p>

<pre><code>function getCursorPos()
{
var cursorPos=-1;
if (window.getSelection)
{
    var selObj = window.getSelection();
    var selRange = selObj.getRangeAt(0);
    cursorPos =  findNode(selObj.anchorNode.parentNode.childNodes,
                        selObj.anchorNode) + selObj.anchorOffset;
/* FIXME the following works wrong in Opera when the document is longer than 32767 chars */
    }
    else if (document.selection)
    {
        var range = document.selection.createRange();
        var bookmark = range.getBookmark();
/* FIXME the following works wrong when the document is longer than 65535 chars */
        cursorPos = bookmark.charCodeAt(2) - 11; /* Undocumented function [3] */

    }

return cursorPos;
}

function findNode(list, node)
{
    for (var i = 0; i &lt; list.length; i++)
    {
        if (list[i] == node) 
        {
            return i;
    }
    }
    return -1;
}
</code></pre>

<p>Is there any other method to do this?
The new element may be in the middle of the HTML ie, it may not be always at the end.</p>

<p>Thank You</p>
