I see that you are using Rangy, but I am not using it at all. Before I realized what Ranks were, I looked at how to get the current selection. I found a function that receives it and replaces it with the passed value. I finished modifying it, but here it is:
http://jsfiddle.net/fjYHr/1/
$(document).ready(function () { $("#setlink").click(function () { replaceSelectedText("jumplink"); }); }); function replaceSelectedText(nameValue) { var sel, sel2, range; if (window.getSelection) { sel = window.getSelection(); sel2 = ""+sel;
Notice how I save the original current selection and then replace it with the <a> element, which gets its name with the passed value.
As for the document.selection part (which is apparently used by IE and 9), I am not 100% sure that the code I provided will work (actually allow the HTML in the selection and not escape from it), But this my attempt :)
source share