When working in a contentEditable-DIV, my goal is to extract the HTML code from the starting position (0) to the end position where the user has clicked.
<div id="MyEditableId" contentEditable="true">
1. Some text 123. <span style="background-color: #0CF;">text 123</span> 456 <span style="background-color: #9F3;">2-> abc </span>
<br />
<p> E.g. here is clicked: "click" Text after click </p>
<p></p>
<br />
end of text.
</div>
I am currently using the code snippet below to retrieve the selected text from 0 to the end of the clicked node. However, I also need to capture the HTML code within the contentEditable-DIV.
$('#MyEditableId').on('mouseup', function(event) {
var MyEditable = document.getElementById('MyEditableId');
MyEditable.focus();
range = document.createRange();
// endOffset: It will be better the length of where actually was clicked, e.g. after 15-characters. But this.length will be also ok.
endOffset = $(this).length;
range.setStart(MyEditable.firstChild,0);
range.setEnd(event.target,endOffset);
var selection = window.getSelection();
selection.addRange(range);
// Below I get the selected text from 0 to end of clicked node. But I need the selected HTML-Code from 0 to end of clicked position.
alert( window.getSelection() );
});
The desired output should resemble the following:
1. Some text 123. <span style="background-color: #0CF;">text 123</span> 456 <span style="background-color: #9F3;">2-> abc </span>
<br />
<p> E.g. here is clicked: "click"
If anyone knows how I can obtain the HTML code instead of just the text in my contentEditable-DIV, your help would be greatly appreciated. Thank you!