I have a textarea
containing HTML, and a div
rendering this HTML.
What I'd like to do is getting the selection positions (start
and end
) in the innerHTML
whenever I select text either in the textarea
or in the div
.
I already managed to get the positions when I select text in the textarea
(as there are easy ways to do it for either textarea
or input
), but I struggle with the div
part.
This answer helped me getting the selected HTML, but there are two problems with this:
- If the same piece of HTML is present twice, using
string.indexOf
to get the position will always get me the position of the first occurrence - Whenever I select a part of an element (may it be
<li>
,<u>
,<b>
,<i>
, etc), the function adds the corresponding tag, so the selected HTML does not match theinnerHTML
.- Say if I select
tu</b></li><li><i>Pi
in the example below, I will get<li><b>
tu</b></li><li><i>Pi
</i></li>
instead.
- Say if I select
updateDiv();
function updateDiv() {
$("#myDiv").html($("#myArea").val());
}
function myTest() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
if(html.length > 0)
alert(html);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea id='myArea' onchange='updateDiv();' rows='12', cols='40'>
<ol>
<li>Patata</li>
<li>
Petete
<ul>
<li><b>Pututu</b></li>
<li><i>Pititi</i></li>
<li>Pututu</li>
</ul>
</li>
</ol>
</textarea>
<div id='myDiv' onclick='myTest()'>
</div>
I'd like to be able to perform actions on the content of my textarea
based on the selected HTML (hence why I need to get the selection position relative to the div
innerHTML
).