This week I was trying to replicate "hyperlink" functionality using a ContentEditable area, rather than a <textarea>. Stupidly, I thought the process of finding a user's currently selected text and surrounding it with a link would be fairly easy... it turned out to be fairly tough.
My function would use the window.getSelection() to get the user's current selection, and then call getRangeAt(0).cloneRange() to create a copy of the "Range" object for that selection. The range object tells the browser where the selection starts and where the selection ends.
I would pull the selected text out into a string object by calling .toString() on the Range object itself. Then I could modify that string to include an <a> tag surrounding it, with the appropriate link. The next step was the most difficult to figure out, the process is as follows:
- Create a new text node, using document.createTextNode and passing in the modified string.
- Call "insertNode" on my range object, passing the text node as a parameter.
- Call "removeAllRanges()" on the selection object, to remove any existing ranges.
- Call "addRange" on the selection object, passing in my modified range object.
This resulted in the selected text being replaced with my linked version in every browser except... Firefox. Bit of a strange one, really, and Googling the issue didn't seem to shed much light. My next step is to find a Firefox friendly fallback for if the normal method fails.