Javascript - 替换选择后无法获取所选文本的父项

Javascript - Cannot Get Parent Of Selected Text After Replacing The Selection

我正在尝试获取所选文本的最近父元素,如果所选文本未被替换,它可以工作,但在文本替换后失败。

这是代码(我从其他来源修改):

jQuery(document).ready(function($){
    $("#getparent").on("click touch", function(){
        var selection, elements = [], ranges = [], rangeCount = 0, parent_id, parent_class;     
        if (window.getSelection){
            selection = window.getSelection();
            if (selection.rangeCount) {
                var i = selection.rangeCount;
                while (i--) {
                    selectionrange = selection.getRangeAt(i);
                    ranges[i] = selectionrange.cloneRange();

                    // SELECTION START'S CONTAINER                  
                    var parentDataStart = selectionrange.startContainer.childNodes[ranges[i].startOffset];
                    parentDataStart = parentDataStart || selectionrange.startContainer.parentNode;
                    var parentTagStart = parentDataStart.tagName.toLowerCase(); // parent tag name of selection

                    console.log(parentTagStart);
                    alert(parentTagStart);

                    // SELECTED TEXT NODE
                    selectedtext = selection.toString();                    
                    elements[i] = document.createTextNode(selectedtext);
                    ranges[i].deleteContents();
                    ranges[i].insertNode(elements[i]);
                    ranges[i].selectNode(elements[i]);
                }

                // Restore text selection
                selection.removeAllRanges();
                i = ranges.length;
                while (i--) {
                    selection.addRange(ranges[i]);
                }
            }
        }
    });
});

这是一个 Fiddle

DEMO

节点选择边界应移动到节点的内容。 因此,请改用 selectNodeContents

对于那个问题,应该是: ranges[i].selectNodeContents(elements[i]); 而不是 ranges[i].selectNode(elements[i]);

更新:

Fiddle Demo