How can I replace the selected text with another text using PURE javascript, in Firefox?
This I use to get the selection:
var sel = this.getSelection();
var range = sel.getRangeAt(0);
And also this important issue:
I want to keep the original format of characters (of course the new string will have the right format )
The selection can be done “cross-elements” (by this I mean that the selection can contain some text from one element like div or table and some text from another elements).
example, the document:
<div>
this is a test
</div>
<div>
<b>still a test</b>
</div>
<table style="width:100%;">
<tr>
<td>
another word</td>
<td>
stackoverflow</td>
</tr>
<tr>
<td>
bump</td>
<td>
</td>
</tr>
</table>
the user select the following text (via one selection):
his is a test still a test anot
So now I want to replace the text keeping the format, for instance replace every thing with new string =
XXX XX X XXXX XXXXX X XXXX XXXX
Final document (after replace) will be:
<div>
tXXX XX X XXXX
</div>
<div>
<b>XXXXX X XXXX</b>
</div>
<table style="width:100%;">
<tr>
<td>
XXXXher word</td>
<td>
stackoverflow</td>
</tr>
<tr>
<td>
bump</td>
<td>
</td>
</tr>
</table>
Wooove, that was a pitty!
Javascript
Example
You can try the code of course
Maybe it’s not the optimal solution, since it starts searching for the start node from the root. It would be faster to search from the first common parent element of
range.startContainerandrange.endContainer, but I don’t know how to do that…Edit
I wrapped the to-X functions inside
if(range.collapsed == false)and usedrange.commonAncestorContainer.childNodes[0]in order to start iterating through the elements from the first child of the common parent of the start and end position of the selection