samedi 25 juin 2016

Failed to Execute 'setStart' on 'Range' when inserting html into content editable div


I'm trying to add html to a content editable div at the specific cursor position. The insert works fine, however, the exception is raised when the cursor needs to be placed after the newly inserted html.

Here is my jQuery extension:

$.fn.extend({
insertTextAtCaret: function (content) {
    var contentLength = 0;
    if (content.indexOf("<") == 0) {
        $(content).each(function (i) {
            contentLength += $($(content)[i]).text().length;
        });
    }
    else
        contentLength = content.length;
    console.log(contentLength);
    var position = window.getSelection().getRangeAt(0).startOffset;
    var innerHtml = $(this).html();
    var pre = innerHtml.substring(0, position);
    var post = innerHtml.substring(position, innerHtml.length + (contentLength - 1));
    if (position == innerHtml.length && content == "n")
        content += content;
    $(this).html(pre + content + post);
    var remove = $(this).find("a.remove-placeholder");
    if (remove)
        remove.click(function () {
            $(this).parent().remove();
        });
    var textNode = $(this)[0].firstChild;
    var range = document.createRange();
    range.setStart(textNode, position + contentLength);
    range.setEnd(textNode, position + contentLength);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);

}

});

And here is my control:

var editableDiv = div.find("#command-expectedResult-" + uuid);
editableDiv.insertTextAtCaret("<span class="remove-placeholder-wrapper" contenteditable="false"><span>[PLACEHOLDER]</span><a class="remove-placeholder">X</a></span>");

So the exception

Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': The offset 21 is larger than or equal to the node's length (7). gets raised on range.setStart.

I think it has to do with the fact that after the html has been inserted at the cursor position, the length is now out of bounds when trying to set the range.

Any help on how to fix this please?


Aucun commentaire:

Enregistrer un commentaire