I have a div with contenteditable=true and a button for changing text div selected text onclick.
Div editable:
<div class="content" id="articleEditor" contenteditable="true"></div>
Style Options
<div class="editor-option">
<button id="changeText">change</button>
</div>
Js file
function replaceSelectedText(replacementText){
if (window.getSelection().rangeCount) {
range = window.getSelection().getRangeAt(0);
range.deleteContents();
var el = document.createElement("span");
el.innerHTML = replacementText;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(document.createTextNode(replacementText));
}
}
$('button').click(function(){
replaceSelectedText('<span class="bold">'+window.getSelection().toString()+'</span>');
})
Now it works for all text selection except the last word. If I select the last word and then I click on the button, the selection is bold but everything I write after is bold too.
How to fix this ?