I need split element (inside editable div) from the cursor position into two parts, Then insert a custom element between it.
before making changes: (vertical line "|" Shows the position of the cursor. I used the "|" to show where the position of the cursor to you. But in reality, this character does not exist in the text.)
<div contenteditable="true">
<span style="font-size='14px'">this is | a test</span>
<p>other paragraphs .....</p>
</div>
after making changes:
<div contenteditable="true">
<span style="font-size:'14px'">this is </span><span style="font-size:'16px'">new text|</span><span style="font-size:'14px'">a test</span>
<p>other paragraphs .....</p>
</div>
It should be noted that after making changes, the cursor must be inserted into the new custom element after the last letter.
I try it but :
let sel = window.getSelection();
let range = sel.getRangeAt(0);
if (range.startContainer.parentNode.nodeName === 'SPAN') {
let sel, range, cloneNode1, cloneNode2, cloneText, allContents, contentsBeforeCursor, contentsAfterCursor, newNode
sel = window.getSelection();
range = document.createRange();
range.selectNode(sel.anchorNode);
cloneNode1 = range.commonAncestorContainer.cloneNode();
cloneNode2 = cloneNode1.cloneNode();
cloneText = range.cloneContents();
allContents = cloneText.textContent;
contentsBeforeCursor = allContents.substring(0, sel.anchorOffset);
contentsAfterCursor = allContents.substring(sel.anchorOffset, allContents.length);
cloneNode1.textContent = contentsBeforeCursor
cloneNode2.textContent = contentsAfterCursor
newNode = document.createElement('SPAN');
for (let i = 0; i < cloneNode1.attributes.length; i++) {
let attr = cloneNode1.attributes.item(i);
newNode.setAttribute(attr.nodeName, attr.nodeValue);
}
newNode.style.fontSize = '13px';
range.selectNode(sel.anchorNode.parentNode);
range.deleteContents();
range.insertNode(cloneNode1)
range.insertNode(newNode)
range.insertNode(cloneNode2)
newNode.focuse();
https://jsfiddle.net/nekooee/0h8zcfv4/43/
This is to change the font in the middle of a SPAN. The CKEditor does the same.