简体   繁体   中英

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

I am trying to get the closest parent element of the selected text, it works if the selected text hasn't been replaced, but it fails after the text replacement.

Here is the code (I modified from other source):

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]);
                }
            }
        }
    });
});

And Here is A Fiddle

DEMO

the node selection boundary should be moved to the node's content. So use selectNodeContents instead.

in the case of that question, it should be: ranges[i].selectNodeContents(elements[i]); instead of ranges[i].selectNode(elements[i]);

Update:

Fiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM