The value returned by getSelectedText is a selection, not an element in the DOM. This is why your cal for the html function does not work, the choice does not have this property.
You can do what you want as follows: set the part of the document you want to process as contentEditable , for example, <p> or <div> . When you select inside this area, you can get the HTML element using document.activeElement . If you select outside the contentEdiatble , then activeElement returns a body element. activeElement YOU CAN process:
document.activeElement.innerHTML = document.activeElement.innerHTML.replace (selection, spn);
However, if you make parts of your document editable, other things happen that you might not want. Seriously, if the selected text appears several times, you cannot determine which one was selected, so this cannot be the solution to your problem.
Updated fiddle here
source share